java在内存分配方面的效率比较 [英] java efficiency comparison in terms of memory allocation
问题描述
这可能是一个重复的问题,但我无法找到我正在搜索的内容。如果它存在,抱歉重复。
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;
}
}
我想知道,如果java分配变量<$ c第一个代码中$ c> a n ^ 2次和 j
n次或者两者仅在第二个代码中分配一次。
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.
我在java中尝试了几次,但结果不一致,就像在一次试验中首先是8秒,第二次是9秒,在另一次试用中反过来。所以,我想确定它们是否相等,
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,
谢谢
推荐答案
查看是否存在差异的一种简单方法是检查字节码。
One easy way to see if there's a difference is to examine the bytecodes.
第一个版本编译为:
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
而第二个编译为:
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.
这篇关于java在内存分配方面的效率比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!