What are the differences and traps between reusing instances of objects and creating new ones every time I replace buffers?
Background:
This is for my game engine.
I write TripleBuffer, where I have three versions of each object: the old version, the current version and the future version. Changes to these objects will be made by reading the state from the current version and making changes to the future version. After making changes to all objects (respectively, if applicable), the buffers will be replaced: future objects become current objects, current objects become old objects and old objects?
- either discarded, and new objects will be allocated by iterating over the current objects
- or become future future objects, and their values ββwill be updated (respectively redefined) by iterating over the current current objects.
Explanations:
- reuse: overwriting the values ββof the old instance with the new values, effectively changing the state of the instance
- "new ones / cloning": create a new instance using the data from the old instance and make changes to it
Use Case:
Let's say that about 1000 objects are exchanged at 30 Hz, which means that they need to be recreated 30 times per second, either by cloning the current ones or reusing the old obsolete old ones (redefining their entire state).
They can vary in complexity from 5 properties to hundreds of properties and will always have a depth of at least 2 levels.
(depth not less than 2 levels = buffered objects themselves will contain only a map of other unique objects that make them up)
Recreation as well as reuse will require iterating over current objects and their components (in short: objects that, in turn, create them).
Further considerations:
Other parts of the engine will trigger events and other magic that will work using snapshots at a point in time. Therefore, a decision to recreate or reuse will result in either:
- recreating means that I can safely pass references to an object since the object will become immutable the moment it becomes the current object.
- Reuse means that I will have to create copies of the current object or any part of it that I need, because I cannot guarantee that the event (or other) will be processed before the object is reused.
source share