Rad*_*adu 24 javascript memory sparse-array
我有以下情况:
var large = [a,b,c,d,e,f,g,h,i];
var small = [a2, b2, c2, null, null, null, null, null, null, i2];
Run Code Online (Sandbox Code Playgroud)
其中两个数组的每个元素都是一个对象.
小数组包含与较大数组相关的信息,但不是每个元素都large需要相关元素small,因此我将其设置为null.但是,我仍然需要保持索引相同,所以我可以做类似的事情large[16].id + ': ' + small[16].description.事实上,我有一个大多数null值的数组会导致内存使用量增加吗?
我的问题是我是否会做更好的事情small = [a2,b2,c2,i2],并在属性等设置索引a2.index = 0; b2.index = 1.
我也遇到过使用undefined的建议,有人甚至提到实现链接列表.我不认为我需要实现链表,因为我不经常添加或删除元素.
cod*_*oma 17
数组实际上是具有特殊属性处理的对象,其名称是数组索引.
通过指定'null',您可以使每个属性存在,这将使用非零数量的内存,并且如上所述已经减慢了查找速度.
您可以改为忽略不存在的成员,这将导致稀疏数组:
var small = [a2, b2, c2,,,,,,, i2];
// small == [a2, b2, c2,undefined,undefined,undefined,undefined,undefined,undefined, i2]
Run Code Online (Sandbox Code Playgroud)
编辑
注意,undefined 并采取空间,如果你明确地将其分配给数组元素(或任何变量).要在这种情况下回收内存,您需要明确delete该元素.我的代码示例中显示的初始化样式从不为elided元素分配任何内容,因此它们根本不存在.这可以通过检查这些元素是否作为数组对象的属性来确认:
// 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.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3989 次 |
| 最近记录: |