Say I want to create a new instance foo.
I’ll do it like this:
SomeClass foo = new SomeClass();
Now lets say the object has reached its end (eg. like a colliding bullet in a game) and should be disposed and reinitialized. To reset the object I could either do this:
foo = new SomeClass();
or this
foo.reset();
NB: The reset() method would just reset all the variables from that instance.
Which is the better way to go (when trying to avoid GC)?
Would the first option create a new pointer?
The first option creates a new object and leaves the old one to be collected as garbage (unless there are other live references to it).
One strategy for reducing GC is to maintain an object pool. This would be just a collection of objects that have no current use and are available for reuse. When you are finished with an object, call a method that returns it to the pool. When you need a fresh object, call a method that checks the pool before creating a new object; if the pool is not empty, it would remove an object from the pool and reuse that rather than creating a new object.
When you need a new
SomeClass, callSomeClass.getInstance(). When you are done with an instance, call it’srecycle()method.