最近在使用PMD进行代码缺陷扫描时,有一类问题PMD称为"call to Collection.toArray() may be optimizable"
下面一行为问题代码:
result = (IResearch[]) list.toArray(new IResearch[0]);
PMD对这类问题给出的解决方案如下:
class Foo {
void bar(Collection x) {
// A bit inefficient
x.toArray(new Foo[0]);
// Much better; this one sizes the destination array, avoiding
// a reflection call in some Collection implementations
x.toArray(new Foo[x.size()]);
}
}
再看下ArrayList的<T> T[] toArray(T[] a) 源码:
public <T> T[] toArray(T[] a) {
if (a.length < size)
a = (T[])java.lang.reflect.Array.
newInstance(a.getClass().getComponentType(), size);
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
你就发现如果采用大家常用的把a的length设为0,就需要反射API来创建一个大小为size的数组,而这对性能有一定的影响.
所以最好的方式就是直接把a的length设为Collection的size从而避免调用反射API来达到一定的性能优化.
import java.util.ArrayList;
public class ToArrayTest {
public static void main(String[] args) {
ArrayList al = new ArrayList();
for (int i = 0; i < 10; i++) {
al.add(String.valueOf(i));
}
String[] s1 = (String[]) al.toArray(new String[15]);
for (int i = 0; i < s1.length; i++) {
System.out.println(i+","+s1[i]);
}
String[] s2 = (String[]) al.toArray(new String[5]);
for (int i = 0; i < s2.length; i++) {
System.out.println(i+","+s2[i]);
}
System.out.println("OptimizableToArrayCall");
String[] s3 = (String[]) al.toArray(new String[al.size()]);
for (int i = 0; i < s3.length; i++) {
System.out.println(i+","+s3[i]);
}
}
}
分享到:
相关推荐
Map<br>js文件为 js/utils.js<br>IE6.0 测试通过<br><br>List:<br>add(var obj) //添加一个元素<br>remove(var index) //删除一个元素<br>get(var index) //获取一个元素<br>removeAll() //删除所有元素<br>toArray...
List<string> listS=new List<string>(); listS.Add(str); listS.Add(hello); string[] str=listS.ToArray(); 二、数组转List (从string[]转到List<string>) string[] str={str,string,abc}; List<string> listS=...
<br><br><br><br>(图一)<br><br>根据上篇文章内容,该图该可以等价于如下的二维表格表示:<br><br><br><br>(图二)<br><br>而对应于该表格的是一个ColumnFirstDynamicArray,共有10个结点,每个结点的取值如下表...
下面的代码从VBScript数组myVBArray创建JScript数组myJSArray: <br> var Temp = new VBArray(myVBArray)<br> var myJSArray<br> myJSArray = Temp.toArray()<br> 上述代码首先创建一个临时的VBArray对象,然后...
4.3 System.Linq.Lookup <TKey,TElement> 10 4.4 System.Linq.Expressions.Expression 10 5 接口 10 5.1 IEnumerable 、IEnumerator 10 5.1.1 正常使用 10 5.1.2 C#的 yield 12 5.2 IEnumerable <T> 12 5.3 ...
public static string JsonSerializer<T>(T t) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(); ser.WriteObject(ms, t); string json...
return new DataStore<Map<String, Object>>(records, new ArrayList<Map<String, Object>>()); } return new DataStore<Map<String, Object>>(records, search(pagingSqlBuilder.getPagingSql(sql, ...
List<SelectItem> tempLists = new ArrayList<SelectItem>(); for (CItemType initComboo : initComboos) { tempLists.add(new SelectItem(initComboo.getItemTypeNum(),initComboo.getItemTypeName())); }...
AbstractSecurityInterceptor 中Collection<ConfigAttribute> attributes = this.obtainSecurityMetadataSource().getAttributes(object); //调用这个方法比较 DefaultFilterInvocationSecurityMetadataSource get...
/// <param name="param"></param> /// <returns></returns> public static string IC_Compress(string param) { byte[] data = System.Text.Encoding.UTF8.GetBytes(param); //byte[] data = Convert....
List<string> list = new List<string>(); foreach (DataRow dr in dt.Rows) { if (!Convert.IsDBNull(dr["XlMc"])) list.Add(dr["XlMc"].ToString()); } return list.ToArray(); } 4,数据源绑定: ...
/// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param> /// <returns>解密成功返回解密后的字符串,失败返源串</returns> public static string Decode(string decryptString, string ...
List<T> duplicates = new List<T>( ); for (int i = 0; i < this.Count; i++) { if (this[i].Equals(inputValue)) { duplicates.Add(this[i]); } } return (duplicates.ToArray( )); } 希望本文所述对...
/// <returns></returns> public byte[] CreateQRcode(string UserName) { QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(); qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE; ...
List<string> ids = new List<string>(); for (int i = 0; i < this.myDataGrid_d.Items.Count; i++) { if (((CheckBox)myDataGrid_d.Items[i].FindControl("cb_choice")).Checked) { DataGridItem item = ...
<source>org.expressme.employee.mgmt.flex.FlexServiceImpl</source> <scope>application</scope> </properties> </destination> 服务名称通过 destination 的 id 属性指定,Flex 前端通过该服务名称来...
<source>org.expressme.employee.mgmt.flex.FlexServiceImpl</source> <scope>application</scope> </properties> </destination> 服务名称通过 destination 的 id 属性指定,Flex 前端通过该服务名称来...
ArrayList<File> temp = new ArrayList<File>(); Collections.addAll(temp, subFiles); zipFile.addFiles(temp, parameters); return dest; } zipFile.addFolder(srcFile, parameters); } else { zipFile....
// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param> // <returns>解密成功返回解密后的字符串,失败返源串</returns> public static string DecryptDES(string decryptString, string ...
function move < T> ( arr: T[] = [], movingMap: ArrayRange | ArrayRange[], Opts < T> = { } ) ArrayRange对象包含: from: number -目标索引。 to: number -目标索引。 Opts对象包含: isMutate?: ...