问题描述
这是我正在质疑的一段代码
Here is the piece of code I'm questioning about
for (int i = 0; i < this.options.size(); i++) {
RadioButton butt = this.options.get(i);
//do something with butt
}
如果我把它改成:
RadioButton butt;
for (int i = 0; i < this.options.size(); i++) {
butt = this.options.get(i);
//do something with butt
}
如果这段代码每秒执行 30-50 次,options
大小约为 20,那会怎么样?
how about if this code is to be executed 30-50 times a second with options
being around size 20?
推荐答案
对于所有现实的、可衡量的情况,两者在性能方面绝对没有区别.事实上,我很确定(不可否认,我不确定)它们会导致完全相同数量的分配和参考创建.JVM 创建 N 个引用持有者是愚蠢的.它会简单地重用在第一次迭代中创建的那个,简单地在下一次赋值中给它一个引用.这意味着两种情况都只使用一个引用持有者(假设这是真的).
For all realistic, measurable cases, there is absolutely no difference between the two performance wise. In fact, I'm pretty sure (admittedly I don't know for sure) they result in the exact same number of assignments and reference creations. It would be stupid for the JVM to create N number of reference holders. It would simply reuse the one created during the first iteration, simply giving it the reference in the next assignment. Which means only one reference holder is used for both cases (assuming this is true).
这篇关于在循环内创建对象与在循环前创建一个临时对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!