GC并在for循环中分配值 [英] GC and assigning values in a for loop
问题描述
我有个朋友告诉了我下面的情况,但是我不能给出一个很好的理由。
someArray = .........
int a;
for(int i = 0; i< someArray; i ++){
a = someArray.get(i).length();
//做点什么
}
他告诉我他宣布<$
我以为声明 a
在for循环之外,以避免频繁的垃圾回收。 for循环中的更具可读性和线程安全性。然而,我不能不同意不同的实例 a
如果在for循环。
有什么建议吗?垃圾收集处理对象 。 你所拥有的是一个原始的局部变量 a
它将被分配到堆栈中。
<因此,这个问题的整个前提是错误的。
I have a friend who told me the following but I couldn't give a good reason why.
someArray =.........
int a;
for(int i=0; i < someArray; i++) {
a=someArray.get(i).length();
// Do something
}
He told me that he declared a
outside of the for loop in order to avoid frequent garbage collection.
I thought declaring a
inside of the for loop is more readable and thread safe.
However I couldn't disagree that different instances a
no of iteration will be garbage collected if it's declared inside of for loop.
Any advise for me?
Garbage collection handles objects. What you have is a primitive local variable a
which will be allocated on the stack.
Therefore the whole premise of this question is wrong.
这篇关于GC并在for循环中分配值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!