Home > other >  Does JavaScript have optional manual memory deallocation?
Does JavaScript have optional manual memory deallocation?

Time:09-25

I am aware that JavaScript is a garbage collected language but I don't really mind freeing memory ahead of GC sweeps if it means less pressure on the GC and my application can run a little smoother/more consistently (particularly on low end devices).

I know in C we have free(), is there something similar in JavaScript?

I know this is invalid but is there something simple like:

const myObj = {}
let myText = "Hello World"

delete myObj
delete myText

// Or 
myObj.free()
myText.free()

Where JavaScript knows how to teardown the data

CodePudding user response:

No, there is no manual memory management in JavaScript, just automatic garbage collection. JavaScript was originally designed for use in browsers; if a random webpage could choose to allocate memory in such a way that the garbage collector would never reclaim it without manual intervention, that's basically asking for memory leaks (unintentional or malicious denial of service by the web page).

Similarly, allowing manual frees would also allow you to intentionally corrupt memory or trigger segfaults; for the simplest example, imagine:

var a = {...define object here...};
var b = a;
JSfree(a);
b.literally_anything_i_do_is_going_to_do_something_horrible();

This isn't a reference counted language (not on any modern JS implementation), and the object tree is one way; a and b know about the object they share, but the object has no idea that it's aliased to two names. So when you forcibly free it through one alias, there's no way for the other alias to know it's now a dangling reference. Giving this sort of power to a random webpage is even worse than allowing manual allocation without GC tracking (which is basically just denial of service), because this is the sort of bug that can allow arbitrary reads and writes into process memory (once you've freed it, other stuff can get allocated there, and that dangling reference is the hacker's "in" to start taking over), eventually leading to breaking the browser sandbox and attacking the local OS.

In short: No, you can't do manual memory management, for very good reasons (yes, technically node.js could provide add-ons to JS to allow it since it's not subject to the same risks as web browsers; it does not, because the benefits aren't worth the cost of building and maintaining such a capability for only the most niche of use cases).

  • Related