开发者

How do modern browsers implement JS Array, specifically adding elements?

By this I mean when calling .push() on an Array object and JavaScript increases the capacity (in number of elements) of the underlying "array". Also, if there is a good resource for finding this sort of information for JS, that would be helpful to include.

edit

It seems that the JS Array is like an object literal with special开发者_运维问答 properties. However, I'm interested in a lower level of detail--how browsers implement this in their respective JS engines.


There cannot be any single correct answer to this qurstion. An array's mechanism for expanding is an internal implementation detail and can vary from one JS implementation to another. In fact, the Tamarin engine has two different implementations used internally for arrays depending on if it determines if the array is going to be sequential or sparse.


This answer is wrong. Please see @Samuel Neff's answer and the following resources:

http://news.qooxdoo.org/javascript-array-performance-oddities-characteristics

http://jsperf.com/array-popuplation-direction

Arrays in JavaScript don't have a capacity since they aren't real arrays. They're actually just object hashes with a length property and properties of "0", "1", "2", etc. When you do .push() on an array, it effectively does:

ary[ ary.length++ ] = the_new_element; // set via hash


Javascript does include a mechanism to declare the length of your array like:

var foo = new Array(3);
alert(foo.length); // alerts 3

But since arrays are dynamic in javascript there is no reason to do this, you don't have to manually allocate your arrays. The above example does not create a fixed length array, just initializes it with 3 undefined elements.

// Edit: I either misread your question or you changed it, sorry I don't think this is what you were asking.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜