Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to free up memory from a TypedArray in JavaScript?

Tags:

javascript

I understand fully that the garbage collector will eventually do it's job and free up the memory allocated in a TypedArray in exactly the same way as it would any variable or object (assuming there are no circular references etc).

However, I am doing a lot of continuous processing in a number of WebWorkers and I would therefore like to have this memory freed as soon as possible by the GC. Using normal JavaScript arrays, simply setting array.length = 0; is a good way a doing exactly this, but what about when using TypedArray's?

Would the following result in the memory being freed as soon as possible?

var testArray = new Uint8Array(buffer);

///Do stuff with testArray

tesArray.length = 0;

Or since the TypedArray is simply a view over the ArrayBuffer, would I need to clear the actual buffer itself also? If so, how?

like image 741
gordyr Avatar asked May 11 '17 14:05

gordyr


People also ask

How do I free up memory in JavaScript?

To release memory, assign the global variable to null . window. users = null; I want to make this article as easy to understand as possible.

How do I clear memory in node JS?

So how would I do that? There is no memory management in js, you can make sure that the object you created are not being used anywhere in the code, then the garbadge collector will free them. It happens automatically. Once your job is finished, the process will be terminated and garbage collector takes care of it.

What is JavaScript Typedarray?

JavaScript typed arrays are array-like objects that provide a mechanism for reading and writing raw binary data in memory buffers. Array objects grow and shrink dynamically and can have any JavaScript value. JavaScript engines perform optimizations so that these arrays are fast.

Can JavaScript access memory?

In contrast, JavaScript automatically allocates memory when objects are created and frees it when they are not used anymore (garbage collection).


1 Answers

Nulling the references to the typed array should be good enough. Setting .length = 0 does not work, as - in contrast to usual arrays - the length property is readonly.

Should you really experience problems with the garbage collector, I would recommend to try reusing the same buffer over and over, instead of allocating new ones all the time and hoping for them to get freed.

like image 165
Bergi Avatar answered Nov 15 '22 10:11

Bergi