I’m running simulations that involve the creation of a tree.
My tree has a branching factor from 2/3 to 7/8.
Each time i need to expand it i allocate an array for the child.
Quite often i make a single branch the new tree(by setting a child of the root as the root), so the rest of my tree become garbage.
I’m wondering if it is better to let the garbage collector do his work (i “suggest” him to start collecting with System.gc() when i change the tree root) or implement my own pool for TreeNodes, and when i change the root, recycle all the now useless nodes.
The answer can be read as: is the android garbage collector very optimized or is it preferable to limiting the creation/destruction of object, even if this is quite consuming?(i would need to traverse all the tree, and append each useless node to a stack for my pool)
I read that android GC is not as “evolved”(it basically runs when you have low memory.) In addition i don’t know if just deleting every reference to the root of the tree will let the gc garbage collect all the tree in a single pass, or it will gc only the node, then the children of that node the next pass, and so on..
To start with, you need to understand if GC is even a worry for you. So run your app with -verbosegc. If your GC reports performance issues or a memory build up you can worry about it. Else eliminate it from your equation of things to do.
The GC works on generations. Basically your allocations are separated into generations. As your app loads all allocations fall under generation 0. And as the app progresses your allocations are put into Generation 1 and 2. The GC when it runs does not work very often on Generation 0 as it would on 1. Similarly it would not run more often on generation 1 as it would on 2. This is done with the assumption that objects that you allocate at load time dont need to be freed as often as objects created later on.
Interesting quote from http://chaoticjava.com/posts/how-does-garbage-collection-work/
life-line.
variables, and some are long-lived such as the backbone of the
application.
made possible with the understanding that in an application’s
lifetime, most instantiated objects are short-lived, and that there
are few connections between long-lived objects to short-lived
objects.