java - Reusing instances of objects vs creating new ones with every update -


what differences , pitfalls between reusing instances of objects vs creating new ones, every time swap buffers?

background:

this game engine project of mine.

i writing triplebuffer have 3 versions of every object: old version, current version, , future version. changes on these objects made reading state current version of , applying changes future version. after changes have been made objects (resp. applicable), buffers swapped: future objects become current objects, current objects become old objects, , old objects?

  • either discarded , new objects allocated iterating on now current objects
  • or become now future objects , values updated (resp. overridden) iterating on now current objects.

explanations:

  • "reusing": overwriting values of old instance new values, changing state of instance
  • "new ones/cloning": creating new instance using data of old instance, , applying changes it

use case:

say 1000 objects swapped @ 30hz, meaning need recreated 30 times second either cloning current ones or reusing obsolete last old ones (overriding state).

they can range in complexity 5 properties hundreds of properties , have depth of @ least 2 levels.

(depth of @ least 2 levels = buffered objects contain map of other unique objects make them up)

recreating reusing both require iterate on current objects , components (shorter than: the objects in turn make them up).

further considerations:

in other parts of engine there event firing , other magic work using in-time snapshots of objects. hence decision of recreating or reusing lead either:

  • recreating means can safely pass on references object, object become immutable @ time becomes current object
  • reusing means have create copies of current object or whatever part of further need, cannot guarantee event (or whatever) processed before object gets reused

unless have reason otherwise, discard old objects , create new ones.

this reduce chances various bugs. example, if there's reference old object somewhere else, re-using may have bad side-effects. discarding , creating new objects cleaner conceptually , make code easier read, debug , maintain.

in general case, garbage collector smart enough make discarding , re-creating object not expensive.

what in situation write clearest, straight-forward code, means creating new object whenever need it. test see if that's performance bottleneck, , if is, @ optimization. in other words, try avoid premature optimization.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -