问题
This may be a duplicate question but I couldnt find what I am searching. If it exists, sorry about duplication.
I want to learn that if the following part of codes are same in terms of memory allocation.
//first
int n = some_number;
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
int a = something;
}
}
//second
int i, j, a;
for(i = 0; i < n; i++){
for(j = 0; j < n; j++){
a = something;
}
}
I wonder, if java allocates the variable a
n^2 times and j
n times in the first code or both are allocated only once as in the second code.
I tried this couple of times in java but the results are inconsistent like in one trial first is 8 sec, second is 9 sec, in another trial reverse. So, I want to make sure if they are equal or not,
Thanks
回答1:
One easy way to see if there's a difference is to examine the bytecodes.
The first version compiles to:
public static void f();
Code:
0: bipush 100
2: istore_0
3: iconst_0
4: istore_1
5: goto 26
8: iconst_0
9: istore_2
10: goto 18
13: iconst_3
14: istore_3
15: iinc 2, 1
18: iload_2
19: iload_0
20: if_icmplt 13
23: iinc 1, 1
26: iload_1
27: iload_0
28: if_icmplt 8
31: return
whereas the second compiles to:
public static void g();
Code:
0: bipush 100
2: istore_3
3: iconst_0
4: istore_0
5: goto 26
8: iconst_0
9: istore_1
10: goto 18
13: iconst_3
14: istore_2
15: iinc 1, 1
18: iload_1
19: iload_3
20: if_icmplt 13
23: iinc 0, 1
26: iload_0
27: iload_3
28: if_icmplt 8
31: return
If you compare them closely, you'll see that they are essentially identical.
Stylistically, I think it's preferable to declare variables as close as possible to their first use. With this in mind, I'd choose the first version over the second.
来源:https://stackoverflow.com/questions/15942926/java-efficiency-comparison-in-terms-of-memory-allocation