null是否占用javascript中的内存? [英] Does null occupy memory in javascript?

查看:217
本文介绍了null是否占用javascript中的内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到以下情况:

var large = [a,b,c,d,e,f,g,h,i];
var small = [a2, b2, c2, null, null, null, null, null, null, i2];

其中两个数组的每个元素都是一个对象。

where every element of both arrays is an object.

小数组包含与较大数组相关的信息,但不是 large 的每个元素都需要中的关联元素所以我把它设置为 null 。但是,我仍然需要保持索引相同,所以我可以做像 large [16] .id +':'+ small [16] .description 这样的事情。事实上,我有一个数值 null 的数组会导致内存使用量增加吗?

The small array contains information related to the the larger one, but not every element of large requires an associated element in small and so I set it to null. However, I do still need to keep the indices the same so I can do things like large[16].id + ': ' + small[16].description. Does the fact that I've got an array that's mostly null in value result in increased memory usage?

My问题是我是否会做更好的事情,比如 small = [a2,b2,c2,i2] ,并在 a2.index = 0; b2.index = 1 等等。

My question is whether or not I'd be better off doing something like small = [a2,b2,c2,i2], and setting indices in properties like a2.index = 0; b2.index = 1 and so on.

我也遇到过使用undefined的建议,有人甚至提到实现链接列表。我不认为我需要实现链表,因为我不经常添加或删除元素。

I've also come across a suggestion to use undefined instead and someone even mentioned implementing linked lists. I don't think I need to implement a linked list since I'm not adding or removing elements very often.

推荐答案

数组实际上是具有特殊处理属性的对象,其名称是数组索引。

Arrays are actually Objects with special treatment of properties with names that are array indexes.

通过赋值'null',您将使每个属性存在,这将使用非零内存量和提到的已经减慢了查找速度。

By assigning 'null', you bring each property into existence, which will use a non-zero amount of memory and as mentioned already slow down lookups.

您可以改为忽略不存在的成员,这将导致稀疏数组:

You can elide the non-existent members instead, which will result in a sparse array:

var small = [a2, b2, c2,,,,,,, i2];
// small == [a2, b2, c2,undefined,undefined,undefined,undefined,undefined,undefined, i2]

修改
请注意 undefined 如果您明确占用空间将它分配给数组元素(或任何变量)。要在这种情况下回收内存,您需要显式删除元素。我的代码示例中显示的初始化样式从不将任何分配给elided元素,因此它们根本不存在。这可以通过检查这些元素是否作为数组对象的属性来确认:

Edit Note that undefined does take space if you explicitly assign it to an array element (or any variable). To reclaim memory in this case, you will need to explicitly delete the element. The initialization style shown in my code sample never assigns anything to the elided elements, so they do not exist at all. This can be confirmed by checking for those elements' existence as properties of the array object:

// continued from above
small.hasOwnProperty('3'); // returns false

small[3] = undefined;
small.hasOwnProperty('3'); // now returns true because the property exists

delete small[3];
small.hasOwnProperty('3'); // returns false again

alert(small.length); // alerts '10', showing that the array itself is still intact.

这篇关于null是否占用javascript中的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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