How to free memory in JavaScript

I work with a canvas and its ImageData object, which contains a huge amount of data (millions of integers). Therefore, working with multiple arrays already takes up a lot of memory (up to 300 MB). Is there any way to free some array memory when it is not needed? I am trying to assign undefined this variable. Right?

+51
javascript memory-management arrays html5-canvas
Dec 11 '11 at 20:49
source share
2 answers

If a variable is stored (for example, global or part of some constant data structure) and the data it points to is large, and you want this data to have garbage collection, then you are right to assign something small to this variable , undefined or null or "" everything will work. What you are doing is clearing the big data link so that it has the right to garbage collection. If nothing else in your javascript refers to this data, it can be freed by the garbage collector. If something else has a link to it, then it cannot be released.

For example, if you have an array of 10,000 elements stored in a global variable:

 var largeDataArray = new Array(10000); 

And you filled most of the elements with data, then you can let this memory have the right to collect garbage by assigning it a different value, for example:

 largeDataArray = null; 

or if you still want this to be an array:

 largeDataArray = []; 

Note: variables that themselves go out of scope (for example, local variables in functions that are not part of a strong closure) or variables in objects that themselves go out of scope should not be cleared manually. When they go beyond or when the parent is deleted, the data contained inside will also have the right to garbage collection.

Thus, purging a variable is only required when you explicitly want to free the data that is stored in a long-lived variable, and usually it only makes sense to worry about it when the data is large or you have a lot that contain up to several megabytes of data (using memory for more high memory levels on smartphones are higher than on desktop browsers).

+79
Dec 11 '11 at 21:20
source share

JavaScript has automatic memory management. A memory containing objects that are no longer referenced will have the right to garbage collection if you do not have a memory leak. Usually there is no need to manually assign undefined variables.

If your program uses too much memory, you must reduce the arrays to get rid of the elements that you no longer need. See Array.pop , Array.shift and Array.splice .

+4
Dec 11 '11 at 20:52
source share



All Articles