【发布时间】:2012-09-18 22:55:45
【问题描述】:
请考虑这两个 Java 代码示例:
// 1st sample
for (Item item : items) {
Foo foo = item.getFoo();
int bar = item.getBar();
// do smth with foo and bar
}
// 2nd sample
Foo foo;
int bar;
for (Item item : items) {
foo = item.getFoo();
bar = item.getBar();
// do smth with foo and bar
}
样本之间的性能/内存消耗有什么不同吗?如果是,那么它是否取决于句柄的类型(对象与原语)?
【问题讨论】:
-
我无法想象这会对编译的字节码产生任何影响。你可以用javap检查。不过,第一个版本更具可读性,并且不会“泄露范围”。
-
我只能看到一个区别。在第二种情况下, foo 和 bar 将在循环外可用。
标签: java performance variables loops