问题描述
我用帆布和蕴含着巨大的数据(百万整数)量的对象的ImageData工作。因此,与一些阵列工作已经需要大量的内存(最大300MB)。有没有一种释放一些阵列的存储时,它的不必要的方法吗?我试图未定义
分配给该变量。是不是?
I'm working with canvas and its ImageData object which contains a huge amount of data (millions of integers). So working with a few arrays already takes a lot of memory (up to 300MB). Is there a way to free up the memory of some array when it's unnecessary? I'm trying to assign undefined
to that variable. Is it right?
推荐答案
如果变量仍然存在(例如,它是全球性或某些持久数据结构的一部分),它指向的数据大,你想要的数据,才有资格垃圾收集,那么你是正确的分配小东西该变量。 未定义
或空
或,
将所有的工作。你在做什么是清除参考大量数据,因此,这将是符合垃圾回收。如果不出意外在JavaScript中有该数据的引用,那么它可以通过垃圾收集器释放。如果别的有对它的引用,那么它就不能被释放。
If the variable persists (e.g. it's global or part of some persistent data structure) and the data it points to is large and you want that data to be eligible for garbage collection, then you are correct to assign something small to that variable. undefined
or null
or ""
will all work. What you're doing is clearing the reference to the large data so that it will be eligible for garbage collection. If nothing else in your javascript has a reference to that data, then it can be freed by the garbage collector. If anything else has a reference to it, then it cannot be freed.
例如,如果你有一个10000元素数组中的一个全局变量召开方式:
For example, if you had a 10,000 element array held in a global variable:
var largeDataArray = new Array(10000);
和,你必须用数据填充大部分元素,那么你可以允许内存分配喜欢它的一些其他的价值,才有资格进行垃圾回收:
And, you had filled most elements with data, then you could allow that memory to be eligible for garbage collection by assigning it some other value like:
largeDataArray = null;
或者如果你仍然希望它是一个数组:
or if you still want it to be an array:
largeDataArray = [];
请注意:变量自身超出范围(如函数的局部变量是不持久的关闭工作的一部分)或变量在自己走出去的范围对象不必手动清除。当他们走出去的范围或当父对象被删除,内包含的数据也将进行垃圾回收。
Note: variables that themselves go out of scope (like local variables in functions that aren't part of a lasting closure) or variables in objects that themselves go out of scope do not have to be manually cleared. When they go out of scope or when the parent object is deleted, the data contained within will also be eligible for garbage collection.
所以,一个变量的结算唯一需要做的事情,当你明确要释放的是一个长期持久的变量中的数据和它通常仅与担心这一点,当数据量较大,或者你有很多他们加起来数据的多个兆字节(内存使用较高的关注在较低水平上的智能手机比桌面浏览器)。
So, the clearing of a variable only needs to be done when you explicitly want to free data that is held in a long lasting variable and it's usually only relevant to worry about this when the data is large or you have a lot of them that add up to multiple megabytes of data (memory use is of higher concern at lower levels on smartphones than in desktop browsers).
这篇关于如何释放JavaScript中的内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!