Skip to content

Recycler

Jirka Dell'Oro-Friedl edited this page Mar 13, 2022 · 4 revisions

Garbage Collection

The browser manages memory automatically without the need for creators to care about that. However, the load imposed by memory management often leads to visible and palpable performance issues, making fast paced actions stall for considerable time while the so called garbage collector frees up space occupied by objects that were abandoned in memory. There is no control over when and how the garbage collector sweeps through, so a standard way to avoid performance ditches is to give it as little work as possible.

Recycling

A standard way for this is to reuse objects, which is supported by FUDGE with the Recycler class. Usually, when a variable referencing an object leaves scope, the object loses the connection to that variable and sits in memory waiting for the garbage collector. Hand the object over to the recycler instead, which will keep a reference. And instead of creating new objects with new, ask the Recycler for that type of object and it will hand you out a used one or create one for you. This way, overall memory management and performance drops by the garbage collector can be minimized.

Rules

  1. Try to use the Recycler most prominently with very frequent creation of objects, that has the biggest impact.
  2. Try to hand back objects for recycling as much as possible. Be careful to make sure that the object is not referenced from anywhere else though!
  3. Do not rely on constructor parameters. If the recycler needs to create a new object, since it ran out of recycled ones, it does not know any parameters to call it with. Rather create an initializing method in that objects class and call that after retreiving the object from the Recylcer.
  4. In rare cases, you may also "borrow" one object from the recycler for use in very small scope. The recylcer will not remove it from its lists so you don't need to hand it back, when leaving scope. Be careful that there will be no references created to that object and no other object gets fetched from the recycler while the borrowed object is used!

RecycableArray

FUDGE implements a class for recycling arrays of objects. Instead of frequently creating new arrays, which leaves formerly created ones to the garbage collector, RecycableArrays offers the methods on arrays with a length counter, that is independent of the real size of the arrays. This way, an array can be reused and treated like a new array, without allocating memory. The functionality is limited and geared specifically for this purpose.

Clone this wiki locally