Skip to content

Memory management

Christian Durán Carvajal edited this page Dec 5, 2020 · 1 revision

Memory management

As D and Javascript have different garbage collectors, care must be taken when sending pointers of D objects to Javascript, as they might have a shorter lifetime in D than in Javascript. There are also ways to create Javascript scopes in D, so that unused JS objects created in D can be collected. This is especially useful inside loops.

Automatically managed

All eager by-value JS to D (see Conversions) conversions create a D value that doesn't have a JS reference, so you don't need to do anything. JSObj and JSVar have a reference counter that allows those objects to also be kept alive on JS while they're alive in D. Consider using inJSScope to allow early collection of stack values.

Creating Javascript scopes

When creating JS values, for example when getting fields of an object, javascript values might be kept alive as the JS environment considers any call to D as a single scope. Sub-scopes might be added using the inJSScope template:

void withSomeObj (JSVar someObj) {
   foreach (i; 0..10000) {
      inJSScope!( () {
         someObj ["someField"] = i;
      });
   }
}

Without the inJSScope, 10 000 JS values would be kept alive.