Recently I came across the types of array declaration in java like,
int[] arr = { 1, 2, 3, 4, 5 };
int[] arr1 = new int[5];
arr1[0] = 0;
arr1[1] = 1; ..etc
Can anyone please explain what will be difference between these two things, like in memory allocation, access efficiency or any other?
They're equivalent (assuming you actually change the values in the first one to 0, 1, 2, 3, 4.)
Indeed, they'll even compile to nearly the same bytecode; Java bytecode doesn't have anything cunning to make this simpler, so the compiler almost just expands the "inline" version to the "create and populate" version.
You can see this by compiling a short test app:
public class Test {
private static void inline() {
int[] x = { 0, 1, 2 };
}
private static void explicit() {
int[] x = new int[3];
x[0] = 0;
x[1] = 1;
x[2] = 2;
}
}
And then using javap
to show the bytecode:
$ javap -c --private Test
Compiled from "Test.java"
public class Test extends java.lang.Object{
public Test();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
private static void inline();
Code:
0: iconst_3
1: newarray int
3: dup
4: iconst_0
5: iconst_0
6: iastore
7: dup
8: iconst_1
9: iconst_1
10: iastore
11: dup
12: iconst_2
13: iconst_2
14: iastore
15: astore_0
16: return
private static void explicit();
Code:
0: iconst_3
1: newarray int
3: astore_0
4: aload_0
5: iconst_0
6: iconst_0
7: iastore
8: aload_0
9: iconst_1
10: iconst_1
11: iastore
12: aload_0
13: iconst_2
14: iconst_2
15: iastore
16: return
}
(Compiled with the stock JDK 7. Of course exact compiler behaviour may vary.)
The only difference is that the "inline" version uses dup
to access x
each time, instead of using aload_0
.
Memory usage will be the same, and I'd expect the JITted code to be identical (as it should be able to spot that aload_0
and dup
are doing the same thing here).
See more on this question at Stackoverflow