On Garbage Collecting C++ Addons in NodeJS

NodeJS Addons are C++ objects that can be loaded into NodeJS using require(). Idea is that this allows NodeJS to gain performance and functionalities of C++. This acts as an interface between JavaScript and C++. NodeJS documentation is helpful to get familiar with Addons>>.

220px-Node.js_logo.svg

However, when it comes to garbage collecting (GC), the documentation is missing some important… well I’d refer to those as tricks.

Manually execute GC,

First we have to set the object instance to null and then call the garbage collector in global context.

obj = null;

global.gc();

One consideration with above is that this is not a reliable way to trigger GC on weak handles.

Another approach is to allocated a huge amount of memory so that GC will triggered,

for (let i = 0;  i < 1e6;  ++i) {

({});

}

Also, the GC can be triggered forcefully using V8’s command line flags –gc_global and —gc_interval. –gc_global forces V8 to perform a full garbage collection, while –gc_interval forces V8 to perform garbage collection after a given amount of allocations.

These command line flags are provided by underlying V8 JavaScript engine. They are subjected to change or removal at anytime and not documented by NodeJS or V8. Therefore it is recommended not to use these outside of testing purposes.

References,

Rock on!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s