What are the differences and pitfalls between reusing instances of objects vs creating new ones, every time I swap buffers?
Background:
This is for a game engine project of mine.
I am writing a TripleBuffer where I have three versions of every object: an old version, a current version, and a future version. Changes on these objects will be made by reading state from the current version of it and applying changes to the future version. After changes have been made to all objects (resp. where applicable), the buffers will be swapped: the future objects become the current objects, the current objects become the old objects, and the old objects?
- either get discarded and new objects will be allocated by iterating over the now current objects
- or become the now future objects and their values will be updated (resp. overridden) by iterating over the now current objects.
Explanations:
- "reusing": overwriting the values of an old instance with new values, effectively changing the state of the instance
- "new ones/cloning": creating a new instance using the data of an old instance, and applying changes to it
Use Case:
Say some 1000 objects are swapped at 30Hz, meaning they need to be recreated 30 times a second by either cloning the now current ones or by reusing the now obsolete last old ones (overriding all their state).
They can range in complexity from some 5 properties up to hundreds of properties and will always have a depth of at least 2 levels.
(depth of at least 2 levels = the buffered objects will themselves only contain a map of other unique objects that make them up)
Recreating as well as reusing will both require to iterate over the current objects and their components (shorter than: the objects that in turn make them up).
Further considerations:
In other parts of the engine there will be event firing and other magic that will do work using in-time snapshots of the objects. Hence the decision of recreating or reusing will lead to either:
- recreating means I can safely pass on references to the object, as the object will become immutable at the time it becomes a current object
- reusing means I will have to create copies of the current object or whatever part of it I further need, as I cannot guarantee that the event (or whatever) will be processed before the object gets reused