Finalizers for JavaScript objects
Asked Answered
T

2

15

Suppose I have some asm.js code, probably created by emscripten. Suppose it has some kind of rather large heap allocated structure, which gets returned by a asm.js function as a pointer that is picked up by some JavaScript library to be wrapped in a nice JavaScript object. Fine so far.

But what happens if that object goes out of scope and gets garbage collected. Right now, the asm.js code has no way of knowing about that, so the memory of the structure will remain allocated, causing a memory leak.

Is there some way to add a finalizer to a JavaScript object from within JavaScript?

Such a finalizer could be used to deallocate the memory in asm.js, thus avoiding the memory leak. So far I couldn't find a documented i.e. portable way to achieve this, but perhaps I've been looking in the wrong places.

Trug answered 28/11, 2013 at 12:46 Comment(2)
@user3075942: Not really: that question is concerned about the when while I don't care about the time as long as I'll get notified of the event. Java has garbage collection and finalizers, and I was hoping for something similar in javaScript.Trug
Actually that question has slightly misleading title, in practice its author asks for destructor/finalizer in JS. See also Javascript's equivalent of destruct in object modelPinball
T
7

Coming back to this question, I found another answer pointing out that there is a specification for weak references and finalization which some browsers implement. The central component for finalization is FinalizationRegistry.

So depending on which browsers you target, this may be possible now. If you need to support browsers without this feature, using explicit release calls, it might be possible to use the finalizers where supported to detect memory leaks (i.e. objects not explicitly released in JavaScript code) and let the developer know so they can fix this.

Trug answered 18/7, 2020 at 8:51 Comment(0)
E
3

The simple answer is that there is no support for this.

Since asm.js code needs to manage its own memory, everything that interacts with objects stored on the asm side need to respect the memory manager that asm uses rather than the memory manager that the browser uses. The best that you can do is to explicitly call a method on any object referencing internal asm memory whenever you create or destroy a reference to it.

Efficiency answered 25/10, 2014 at 21:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.