Reputation: 905
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
}
would I gain a huge performance improvement if I changed it to:
RadioButton butt;
for (int i = 0; i < this.options.size(); i++) {
butt = this.options.get(i);
//do something with butt
}
EDIT: how about if this code is to be executed 30-50 times a second with options
being around size 20?
Upvotes: 1
Views: 1241
Reputation: 3767
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).
Upvotes: 4
Reputation: 33515
I think code and performance is almost same only looks different. You are not creating new instances but only copy references of objects from your collection.
But i like and usually use second approach.
Upvotes: 2
Reputation: 40436
Looking at the title, I knew this was going to be yet-another-misguided-performance-question.
A couple of things:
As for the GC comment you made in another answer: The GC happens in the background, is intelligent, and makes decisions that you have absolutely zero control over (aside from JVM command line tuning -- don't get excited, based on the fact that you asked this question, you probably aren't equipped to make good decisions about tuning parameters). Moving the reference from one place to another gives you no significant measure of control over how the GC handles it. Each time through the loop the previous reference is no longer reachable, the GC will clean it up at an undefined point in the future.
Upvotes: 3
Reputation: 1102
In both cases you are creating the RadioButton
object in the loop because RadioButton butt
it's only a refernce and not an instance of the object. Presumably is this.option.get(i)
which creates your object.
So my answer is: no.
The only thing that changes is that in the second loop you're creating this.options.size()
-times the reference butt
Upvotes: 0
Reputation: 40228
You're not creating objects here, you're just creating references, and whether you're creating one reference or more doesn't really matter.
Upvotes: 3
Reputation: 2238
The difference is not huge as assignment of the object is the biggest cost here. Also, the compiler will make your code more efficient, so in the end it is the same cost in performance.
Upvotes: 0