I am currently trying to avoid GC_CONCURRENT calls, so i’m running through my main loop.
I’ve noticed that i often create a complex object to do calculations.
So my question is would declaring that object as a field of the class opposed to declaring it in the methods that use it help performance?
Or because my english has probably hurt you brain, here’s the code example as field
class myclass{
private MyObject myObject;
...
public void myLoopedMethod(...){
myObject = new MyObject(...);
myObject.dostuff;
}
Example in method
class myclass{
...
public void myLoopedMethod(...){
MyObject myObject = new MyObject(...);
myObject.dostuff;
}
The right scope would be the method, but my doubt is that by making it a field, the memory is always freed and allocated in the same spot. Is this true and does this help avoiding GC calls?
Also, i should probably do something like this, but I’m interested if the above logic makes sense.
class myclass{
private MyObject myObject;
...
public void myMethod(...){
myObject.setNewValues(...);
myObject.dostuff;
}
}
There is no guarantee that memory allocated in the same spot. It is implementation detail.
In your example case, if instance variable, all objects referenced by this instance variable will be eligible for GC except last object which still has a reference from the instance variable (last one will become eligible for GC when it has no reachable references).
In case of defining inside method, all objects referenced by this reference will become eligible for GC as soon as loop done.
So, better go with defining inside method unless you need reference to the object identified in loop.
Coming to question avoiding GC calls, I think both approaches will have almost same amount of GC activity. Unless you have real issue with memory I would suggest don’t worry about memory allocation and GC, VMs are intelligent enough to take care that stuff.