Preferred method to set / return arrays

Compare two ways to set / return an array:

static public float[] test_arr_speeds_1( int a ) {
  return new float[]{ a, a + 1, a + 2, a + 3, a + 4, a + 5,
                      a + 6, a + 7, a + 8, a + 9 };
} // or e.g. field = new float... in method

static public float[] test_arr_speeds_2( int a ) {
  float[] ret = new float[10];
  ret[0] = a;
  ret[1] = a + 1;
  ret[2] = a + 2;
  ret[3] = a + 3;
  ret[4] = a + 4;
  ret[5] = a + 5;
  ret[6] = a + 6;
  ret[7] = a + 7;
  ret[8] = a + 8;
  ret[9] = a + 9;
  return ret;
} // or e.g. field[0] = ... in method

Both generate different bytecodes, and both can be decompiled in their previous state. After checking the execution time through the profiler (iterations 100M, unbiased, different neighborhoods), the time of the _1 method is approx. 4/3 time _2, although both create a new array and both set each field to a given value. The time in most cases is negligible, but it still bothers me - why is _1 noticeably slower? Can someone check / confirm / explain this to me in a reasonable way supported by the JVM?

+5
source share
1 answer

( ). :

bipush  10
newarray float      //creating an array with reference on operand stack

dup
iconst_0
iload_0
i2f
fastore             //setting first element

dup
iconst_1
iload_0
iconst_1
iadd
i2f
fastore             //setting second element

//...
areturn             //returning the top of the operand stack

:

bipush  10
newarray float
astore_1            //creating an array and storing it in local variable

aload_1
iconst_0
iload_0
i2f
fastore             //setting first element

aload_1
iconst_1
iload_0
iconst_1
iadd
i2f
fastore             //setting second element

//...
aload_1
areturn

, , ( dup - fastore), ( ). (aload_1), fastore , arrayref .

- - , , CPU. .

, ​​ - , . , "" ( JVM/ ). - , , .

+6

All Articles