Hacker News new | ask | show | jobs
by ladon86 1097 days ago
When writing a game in JS, it’s very important to minimize garbage collection - too much will cause periodic stuttering and freezes. To avoid GC you want to minimize runtime allocations and mostly allocate upfront and reuse that memory.

One way is to use object pooling, but doing so in JS can be brittle because you have to remember to manually call `Pool.release(obj)`, `obj.free()` or whatever method you’ve chosen to return an object to the pool.

If a developer forgets to do this, you could exhaust the object pool, or if it’s growable, cause a memory leak! In a game’s update loop that could happen very quickly.

With this new feature, you could grab a short-lived object from the pool and automatically return it to the pool at the end of the method or loop.

Example - imagine this is inside an update method called 60 times per second:

  for (const enemy of enemies) {
    using pos = Pool.getVec3();

    // do stuff with pos

    enemy.setPosition(pos);
  } // pos is returned to pool automatically  

You asked about try/catch/finally. The downsides for this use-case are:

* Big performance hit when you use it in a hot loop like this - the disposal could be happening ~10,000 times per second.

* Harder to remember to fill all your loops with try…finally, ugly to have double braces anytime you’re using a pooled object.

* It’s an abuse of syntax if you’re not actually catching any error.