Memory and the GC

LoomScript is primarily a garbage collected language. That is, memory that is no longer referenced is automatically freed rather than requiring an explicit deallocation step. This is very convenient for high level application logic as it removes burden on the developer to manage his or her memory.

Note that if you don't clear references from static variables to unused objects, they will stick around forever since the GC will think they are in use!

Performance Implications

However, this convenience carries some downsides. The garbage collector is a complex process, and it must run from time to time to keep the application from exhausting its memory and crashing. This takes time and affects framerate.

In order to favor consistent performance, the GC is run every frame. This incurs a performance overhead, but it helps avoid spikes. Humans notice irregulaties (like a 100ms hitch when the GC runs), while a consistent rate is much less objectionable.

Churn

Of course, if the application is allocating and freeing (churning) lots of memory, then the GC is going to run a lot more often, and a lot longer. While the trivial case is easy to avoid:

// This will spend most of its time GC'ing unused objects.
for(;;) var foo = new Object();

Real world churn is harder to spot. The best thing to do is simply use the memory profiler (described in the profiler section) to see how many objects were created in a period with bad performance. Almost always, if the GC is the problem, you will see a lot of objects being created with relatively few alive at any given moment. Then it is a matter of refactoring your code to perform fewer allocations (i.e., call new less often) to solve the problem.

Working with Natives

LoomScript can work with native C++ classes. These generally don't get garbage collected on their own since C++ assumes explicit memory management. Instead, you need to call deleteNative() on them when you want to free them.

If C++ code deletes a native instance referenced by LoomScript, then attempts to access that native instance from LoomScript will generate a runtime error (as opposed to a hard crash).

You can dump the currently allocated natives via VM.getExecutingVM().dumpManagedNatives(); if you want to make sure they aren't leaking, or run dumpManagedNatives in the debug console if you don't want to modify your code.