I have these two snippets of code (written in Java) which is more more efficient?
int foo(){
int result;
for(int i = 0; i < n;i++){
SomeObject a,b,c;
a = new SomeObject();
b = new SomeObject();
c = new SomeObject();
//do something with a,b,c
//and derive result
}
return result;
}
or
int foo(){
int result;
SomeObject a,b,c;
a = new SomeObject();
b = new SomeObject();
c = new SomeObject();
for(int i = 0; i < n;i++){
a.flush(); //reset object do not create new though
b.flush(); //reset object do not create new though
c.flush(); //reset object do not create new though
//do something with a,b,c
//and derive result
}
return result;
}
In the second snippet, I have moved the local variables out of the loop, so effectively it creates only one instance of them. Does this improve anything?
Logically, it would make sense when the variables are inside the loop. But would the garbage collector clean up the objects efficiently?
EDIT: Updated the snipped, regarding instantiation of objects.
You’ve moved the variables out, but those aren’t objects. Assuming you’re assigning different values to
a,bandcon every iteration of the loop, you haven’t reduced memory allocation at all – you’ve just widened the scope of variables unnecessarily.If you don’t need to change the values of
a,bandcin the loop then that’s a different matter, and it would be a better idea to assign them outside the loop rather than on every iteration.The main thing is to realize the difference between objects and variables though. In particular, creating “new” variables on each iteration of the loop doesn’t actually cost anything.
EDIT: Okay, with the updated question, there clearly is a difference in terms of how many objects are created. However, depending on exactly what’s going on the second form may still be more preferable: it’s certainly easier to understand, and it doesn’t rely on the details of what the
flushoperation does. On the other hand, if creating an instance ofSomeObjectis expensive (e.g. it generates crypto keys) then it’s a good idea to optimize against that.In short: it depends. Write the most readable code first, measure it, and compare that with your performance requirements. Only move to less obvious code when there’s a demonstrable benefit.