【发布时间】:2012-06-08 23:28:13
【问题描述】:
创建一个给定长度的数组最有效的方法是什么,每个元素都包含它的下标?
我的虚拟代码的可能描述:
/**
* The IndGen function returns an integer array with the specified dimensions.
*
* Each element of the returned integer array is set to the value of its
* one-dimensional subscript.
*
* @see Modeled on IDL's INDGEN function:
* http://idlastro.gsfc.nasa.gov/idl_html_help/INDGEN.html
*
* @params size
* @return int[size], each element set to value of its subscript
* @author you
*
* */
public int[] IndGen(int size) {
int[] result = new int[size];
for (int i = 0; i < size; i++) result[i] = i;
return result;
}
其他提示,例如文档样式,欢迎使用。
编辑
我在其他地方读到过 for 循环与其他方法相比效率低下,例如在 Copying an Array 中:
使用克隆:93 毫秒
使用 System.arraycopy:110 毫秒
使用 Arrays.copyOf:187 毫秒
使用 for 循环:422 毫秒
我对这个网站上一些问题的富有想象力的回答印象深刻,例如,Display numbers from 1 to 100 without loops or conditions。这是一个可能建议一些方法的答案:
public class To100 {
public static void main(String[] args) {
String set = new java.util.BitSet() {{ set(1, 100+1); }}.toString();
System.out.append(set, 1, set.length()-1);
}
}
如果您无法解决这个具有挑战性的问题,无需发泄:只需继续下一个未回答的问题,您可以处理。
【问题讨论】:
-
这似乎行得通。请不要微优化。
-
谁要求你优化这段代码?
-
这个数组有多大是?我们在这里谈论的是兆字节还是千兆字节的数据?
-
@sarnold,目前还不清楚。它可能是 10^12 个元素,或者更多。要求很高的应用程序。
-
所以你需要 3.6 TB 的整数。元素
2147483648会发生什么?整数应该回绕到0或-2147483647,还是要将它们存储在 64 位整数字段中? (这需要 7 TB 的数据。)
标签: java arrays performance