哪个内存更少:Javascript数组或Javascript对象? [英] Which takes less memory: a Javascript array or Javascript object?

查看:147
本文介绍了哪个内存更少:Javascript数组或Javascript对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个只有数字键的Javascript列表,这需要更少的内存?

If I have a Javascript list which will have only numeric keys, which takes less memory?

var array = [];
array[0] = 'hello';
array[5] = 'world';
array[50] = 'foobar';

var obj = {};
obj[0] = 'hello';
obj[5] = 'world';
obj[50] = 'foobar';

我不知道Javascript引擎的内部结构,所以......

I don't know a ton about Javascript engine internals, so...

我问的原因是因为该数组在转换为字符串时会在其中间有一堆未定义的数组。那些实际上是以某种方式存储的,还是刚刚进行字符串转换?

The reason I ask is because that array, when converted to a string, will have a bunch of undefined's in the middle of it. Are those actually stored in some fashion, or is that just put in at string conversion?

推荐答案

数组基本上是一个有序的集合与单个变量名相关联的值。

An array is basically an ordered set of values associated with a single variable name.

在您的示例中,我认为您尝试执行关联数组,并且您应该使用object,不应该使用Array对于键/值对。

In your example I think you try to do an associative array, and you should use object, Array is not meant to be used for key/value pairs.

当您为具有更高当前数组长度的索引分配值时,数组长度也会间接增加:

Also the array length is indirecly increased when you assign a value to an index with higher length of the current array length:

var array = new Array();
array[99] = "Test";
// array.length is now 100

检查这个关于这个主题的详细文章

这篇关于哪个内存更少:Javascript数组或Javascript对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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