简体   繁体   English

我应该清除未使用的javascript数组吗?

[英]Should I clear unused javascript arrays?

I'm working on a page that, eventually, could have more than 100 arrays, only a few of which would be used at any given time. 我正在开发一个页面,该页面最终可能有100多个数组,在任何给定时间都只会使用其中的几个。

At the moment, I'm populating all arrays as global variables, but I suspect this is inefficient in terms of memory use. 目前,我正在将所有数组填充为全局变量,但是我怀疑这在内存使用方面效率低下。

Should I change my code to clear the arrays when they are not being used? 当不使用数组时,是否应该更改代码以清除数组? If so, what is the best way to do this? 如果是这样,最好的方法是什么? I'd guess var myArray = new array() but perhaps there's a better option. 我猜var myArray = new array()但也许有一个更好的选择。

Unless you have many thousands of objects in your arrays, you don't need to worry. 除非阵列中有成千上万的对象,否则您不必担心。 Don't prematurely optimize your code; 不要过早地优化代码; the browser is quite good at handling lots of small objects. 浏览器非常擅长处理许多小对象。

If memory does become an issue or you notice performance issues, you can simply reassign a new array to those variables: 如果内存确实成为问题,或者您注意到性能问题,则只需为这些变量重新分配一个新数组即可:

myArray = [];

The garbage collector will clean up the objects that you dereferenced. 垃圾收集器将清除您取消引用的对象。

In a broader case, if there's no need to keep references to those objects, you don't even need the arrays to begin with. 在更广泛的情况下,如果不需要保留对这些对象的引用,那么甚至不需要数组就可以开始。 Ie, if you never access the elements that you put in the arrays a second time, just remove the arrays and don't bother assigning the data. 即,如果您从不访问第二次放入数组中的元素,则只需删除数组,而不必理会分配数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM