I have two code snippets (written in Java) that are 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();
}
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 fragment, I moved the local variables from the loop, so effectively it creates only one instance of them. Is this improving something? Logically, this makes sense when the variables are inside the loop. But could the garbage collector clean objects efficiently?
EDIT: Updated debugged regarding object creation.
source
share