在循环内部或外部声明一个对象? [英] Declare an object inside or outside a loop?

查看:74
本文介绍了在循环内部或外部声明一个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码段是否有任何性能损失?

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.

这篇关于在循环内部或外部声明一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆