Doing away with Globals?
I have a set of tree objects with a depth somewhere in the 20s. Each of the nodes in this tree needs access to its tree's root.
A couple of solutions:
- Each node can store a reference to the root directly (wastes memory)
- I can compute the root at runtime by "going up" (wastes cycles)
- I can use static fields (but this amounts to globals)
Can someone provide a design that doesn't use a global (in any variation) but is more efficient that #1 or #2 in both memory or cycles respectively?
Edit: Since I have a Set of Trees, I can't simply store it in a static since it'd be hard to differentiate between trees. (thanks maccullt)
Pass the root as a parameter to whichever functions in the node that need it.
Edit: The options are really the following:
- Store the root reference in the node
- Don't store the root reference at all
- Store the root reference in a global
- Store the root reference on the stack (my suggestion, either visitor pattern or recursive)
I think this all the possibilities, there is no option 5.