我认为直接创建起来会更快,但是实际上,添加循环只需要一半的时间。发生了什么,放慢了这么多?
这是测试代码
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public class Test_newArray {
private static int num = 10000;
private static int length = 10;
@Benchmark
public static int[][] newArray() {
return new int[num][length];
}
@Benchmark
public static int[][] newArray2() {
int[][] temps = new int[num][];
for (int i = 0; i < temps.length; i++) {
temps[i] = new int[length];
}
return temps;
}
}
Run Code Online (Sandbox Code Playgroud)
测试结果如下。
Benchmark Mode Cnt Score Error Units
Test_newArray.newArray avgt 25 289.254 ± 4.982 us/op
Test_newArray.newArray2 avgt 25 114.364 ± 1.446 …Run Code Online (Sandbox Code Playgroud) 假设我有两个数组arrayOne并且arrayTwo在哪里arrayOne.length != arrayTwo.length(假设两个List具有不同的类似情况size()).以下任何一种都提供了速度优势吗?
选项1
for(int i = 0 ; i < arrayOne.length ; ++i) {
for(int j = 0 ; j < arrayTwo.length ; ++j) {
//Do something
}
}
Run Code Online (Sandbox Code Playgroud)选项2
for(int i = 0 ; i < arrayTwo.length ; ++i) {
for(int j = 0 ; j < arrayOne.length ; ++j) {
//Do something
}
}
Run Code Online (Sandbox Code Playgroud)java ×4
performance ×2
arrays ×1
benchmarking ×1
jvm ×1
jvm-hotspot ×1
loops ×1
nested-loops ×1