GC optimization: declaring an object as a field opposite to declaring it locally

I'm currently trying to avoid calls to GC_CONCURRENT, so I am looking through my main loop. I noticed that I often create a complex object to perform calculations.

So, my question will be to declare that an object as a class field, the opposite of declaring it in methods that use it, helps performance?

Or because my English probably hurt your brain, here's an example code like a field

class myclass{ private MyObject myObject; ... public void myLoopedMethod(...){ myObject = new MyObject(...); myObject.dostuff; } 

An example in a method

 class myclass{ ... public void myLoopedMethod(...){ MyObject myObject = new MyObject(...); myObject.dostuff; } 

The correct volume will be the method, but I doubt that by creating its field, the memory is always freed and allocated in the same place. Is this true and does it help avoid GC calls?

Also, I should probably do something similar, but I wonder if the logic above makes sense.

 class myclass{ private MyObject myObject; ... public void myMethod(...){ myObject.setNewValues(...); myObject.dostuff; } } 
+4
source share
2 answers

but I doubt that by creating a field, memory is always freed and allocated in the same place. Is this true and does it help avoiding GC calls?

There is no guarantee that memory is allocated in one place. This is an implementation detail.

In your example case, if the instance variable, all objects referenced by this instance variable will be eligible for GC, with the exception of the last object that still has a reference from the instance variable (the last one will be eligible for GC if there are no available links).

If you define an internal method, all the objects referenced by this link will become available to the GC as soon as the loop is executed.

So, better go with the definition inside the method if you don't need a reference to the object identified in the loop.

Starting with the question, avoiding GC calls, I think that both approaches will have almost the same amount of GC activity. If you do not have a real memory problem, I would advise you not to worry about memory allocation and GC, virtual machines are smart enough to take care of this.

+5
source
  • Yes, if creating an object inside a commonly called method, this will lead to more work for the garbage collector.

  • Always measure instead of speculation ... Theoretical benefits may be negligible.

0
source

All Articles