0

Today i was going through some posts in stackoverflow and this reply just popped up. https://stackoverflow.com/a/2280350/548591

https://stackoverflow.com/a/11513602/548591

var name = [];
var name = new Array();

Is the literal one better in terms of performance than initializing an new Array Object.

Was reading this article now, just wanted to update.

http://yuiblog.com/blog/2006/11/13/javascript-we-hardly-new-ya/

4

3 Answers 3

0

From working on my own direct implementation of ECMA Grammar to make a parser, I can tell you this:

The Array literal [] gets parsed directly and then converted into an array object, whereas new Array() gets parsed first as a "expression", then checked for the new keyword, then what you want to create (in this case Array) and is then evaluated.

I can't tell you exactly how much performance is lost by using new Array(), it varies by the Javascript engine. V8 (Chrome) for example, pre-compiles code to optimize it, so it might get converted into a literal [] anyway, depending on how it works.

The easiest way would be to make a test function that creates a few hundred thousand arrays and measures the time for the loop with the literal declaration or the constructor initialization respectively.

Sign up to request clarification or add additional context in comments.

Comments

0

Yeah, according to the tests, initialising [] is much faster than using the new Array. Besides that, the literal version si much more readable.
And this has already been asked!

Comments

0

Depending on the browsers, Literals appear to be up to twice as fast. That is, in browsers where there's a significant difference.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.