Genbox / VelcroPhysics

High performance 2D collision detection system with realistic physics responses.
MIT License
671 stars 114 forks source link

Pooling of user objects #5

Closed Genbox closed 3 years ago

Genbox commented 7 years ago

Object pooling is an optimization method for reducing the load on garbage collectors. Velcro already makes heavy use of pooling for internal objects such as contacts. This proposal extends this capability to user objects such as Body, Shape and Fixture to further reduce the load on the garbage collector.

The proposal is to add an interface to all 'poolable' objects that contain a Reset() method. Each class will be responsible for providing their own implementation of Reset to make sure they have cleaned their internal state completely. Each user object will be extended with a Destroy() method as well, that can be called by the user when the object is no longer needed.

The factory classes will then be made 'pool' aware and fetch one from the pool rather than create a new object.

Advantages:

  1. Reduced load on the garbage collector since we reuse objects
  2. Faster object creation as we reuse existing objects

Disadvantages:

  1. If the user calls Destroy() on an object and uses it afterwards, it will cause havoc.
  2. The engine will use a little more memory since we keep a small number of objects always

Misc:

  1. I can make a setting for this behavior to be turned on and off. Should there be issues with bodies used after Destroy(), it can easily be determined by turning off pooling.
  2. I will probably pre-load the pool with a couple of objects on World creation. This should also be configurable.

Any comments, improvements or votes (thumbs up/down) are appreciated.

Genbox commented 3 years ago

This is too much of a challenge to implement without any unwanted behavior. For now, the engine itself will pool aggressively for internal objects, but user objects will stay in userland. For large games, I suggest pooling bodies (etc.) manually.