Skip to main content
edited title
Link
ilkkachu
  • 6.6k
  • 18
  • 30

Why does the first methodallocating a single 2D array take morelonger than twice as long to create an arraya loop allocating multiple 1D arrays of the same total size and shape?

Became Hot Network Question
Source Link
user10339780
  • 963
  • 1
  • 7
  • 13

Why does the first method take more than twice as long to create an array?

I thought it would be quicker to create directly, but in fact, adding loops takes only half the time. What happened that slowed down so much?

Here is the test code

@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; } } 

The test results are as follows.

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 us/op 

The test environment is as follows

JMH version: 1.21

VM version: JDK 1.8.0_212, OpenJDK 64-Bit Server VM, 25.212-b04