如何在 JavaScript 中释放内存 [英] How to free up the memory in JavaScript

查看:141
本文介绍了如何在 JavaScript 中释放内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用画布及其包含大量数据(数百万个整数)的 ImageData 对象.因此,使用几个数组已经需要大量内存(高达 300MB).有没有办法在不需要时释放某些数组的内存?我正在尝试将 undefined 分配给该变量.是吗?

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?

推荐答案

如果变量持续存在(例如,它是全局的或某些持续数据结构的一部分)并且它指向的数据很大,并且您希望该数据符合条件垃圾收集,那么您为该变量分配一些小的东西是正确的.undefinednull"" 都可以工作.您正在做的是清除对大数据的引用,以便它有资格进行垃圾收集.如果您的 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.

例如,如果您在一个全局变量中保存了一个 10,000 个元素的数组:

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 中释放内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆