JavaScript 数组实际上是作为数组实现的吗? [英] Are JavaScript Arrays actually implemented as arrays?

查看:35
本文介绍了JavaScript 数组实际上是作为数组实现的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript ArrayObject 之间的区别不是很大.实际上看起来Array主要是增加了length字段,所以你可以同时使用Arrays和Objects作为数值数组:

The difference between a JavaScript Array, and Object is not very big. In fact it seems Array mainly adds the length field, so you can use both Arrays and Objects as numeric arrays:

var ar = new Array();
ar[0] = "foo";
ar["bar"] = "foo";

var ob = new Object();
ob[0] = "foo";
ob["bar"] = "foo";

assert(ar[0] == ob[0] == ar["0"] == ob["0"] == ar.bar == ob.bar); // Should be true.

所以我的问题是,在流行的 JavaScript 引擎中 (V8、JavaScriptCore、SpiderMonkey 等),这是怎么处理的?显然我们不希望我们的数组实际上被存储为带有键值的哈希映射!我们如何合理地确定我们的数据存储为实际数组?

So my questions is, in popular JavaScript engines (V8, JavaScriptCore, SpiderMonkey, etc.), how is this handled? Obviously we do not want our arrays to be actually stored as hash maps with key values! How can we be reasonably sure our data is stored as an actual array?

据我所知,引擎可以采用以下几种方法:

As far as I can see there are a few approaches engines could take:

  1. Array 的实现方式与 Object 完全相同 - 作为带有字符串键的关联数组.
  2. Array 是一个特例,它有一个类似 std::vector 的数组支持数字键,以及一些密度启发式方法,以防止在您这样做时出现疯狂的内存使用<代码>ar[100000000] = 0;
  3. ArrayObject 相同,所有对象都会得到启发,看看使用数组是否更有意义.
  4. 一些我没想到的极其复杂的事情.
  1. Array is implemented exactly the same way as Object - as an associative array with string keys.
  2. Array is a special case, with a std::vector-like array backing the numeric keys, and some density heuristic to prevent insane memory use if you do ar[100000000] = 0;
  3. Array is the same as Object, and all objects get a heuristic to see if using an array would make more sense.
  4. Something insanely complicated that I haven't thought of.

如果有合适的数组类型,这真的会更简单( WebGL 类型数组).

Really this would be simpler if there were a proper array type (cough WebGL typed arrays cough).

推荐答案

在 SpiderMonkey 中,数组基本上是作为 jsval 的 C 数组实现的.这些被称为密集阵列".然而,如果你开始对它们做类似非数组的事情——比如把它们当作对象——它们的实现就会改变为非常类似于对象的东西.

In SpiderMonkey, arrays are implemented basically as C arrays of jsvals. These are referred to as "dense arrays". However, if you start doing un-array-like things to them -- like treating them like objects -- their implementation is changed to something which very much resembles objects.

这个故事的寓意:当你想要一个数组时,使用一个数组.当你想要一个对象时,使用一个对象.

Moral of the story: when you want an array, use an array. When you want an object, use an object.

哦,jsval 是一种可变参数类型,可以在 64 位 C 类型中表示任何可能的 JavaScript 值.

Oh, a jsval is a sort of variadic type which can represent any possible JavaScript value in a 64 bit C type.

这篇关于JavaScript 数组实际上是作为数组实现的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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