在循环内部或外部声明一个对象?
问题描述:
以下代码段是否有任何性能损失?
Is there any performance penalty for the following code snippet?
for (int i=0; i<someValue; i++)
{
Object o = someList.get(i);
o.doSomething;
}
或者这段代码实际上更有意义吗?
Or does this code actually make more sense?
Object o;
for (int i=0; i<someValue; i++)
{
o = someList.get(i);
o.doSomething;
}
如果在字节码中这两个完全等价,那么显然第一种方法看起来更好在风格方面,但我想确保是这种情况。
If in byte code these two are totally equivalent then obviously the first method looks better in terms of style, but I want to make sure this is the case.
答
在今天的编译器中,没有。我在最小的范围内声明对象,因为它对下一个人来说更具可读性。
In today's compilers, no. I declare objects in the smallest scope I can, because it's a lot more readable for the next guy.