Writing efficient code and optimizing memory

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();
      //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 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.

+3
source share
5 answers

, . , a, b c , - .

a, b c , , , .

, . , "" .

EDIT: , , , , . , , : , , , , flush. , SomeObject (, ), .

: . , . , .

+4

, . SomeObject , , .

. - -, , SomeObject GC , .

, , new . .

FWIW, : , . , , , , .

+3

, , . , , reset() , .

; , , . , , , .

+1

I really tested this, and there is no difference, because the compiler finds out that option 1 can be done better as option 2 and in any case change it to.

Code for clarity first, second efficiency (the compiler is smarter than you, anyway)

+1
source

It depends, if they get each iteration of the loop in both cases, then none of them is more efficient. If you initialize them outside the loop body, the latter will be faster.

0
source

All Articles