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/

Community
  • 1
  • 1
theJava
  • 14,620
  • 45
  • 131
  • 172
  • Performance questions should be addressed using performance tools (e.g., http://www.jsperf.com). If you have results and want to know *why* one is better than the other, then that's a different question altogether. – apsillers Feb 12 '13 at 13:51
  • 5
    This answer is pretty exhaustive on this topic: [Why arr = \[\] is faster than arr = new Array?](http://stackoverflow.com/questions/7375120/why-arr-is-faster-than-arr-new-array) – Christoph Feb 12 '13 at 13:51
  • See also: http://jsperf.com/new-array-vs-literal-notation, http://jsperf.com/new-array-vs-literal/13, and more generally https://www.google.com/search?q=jsperf+array+literal – apsillers Feb 12 '13 at 13:52
  • Doesn't [that answer](http://stackoverflow.com/a/2280295/1048572) in one of the questions you linked tell enough? – Bergi Feb 12 '13 at 13:54

3 Answers3

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.

xwcg
  • 196
  • 9
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!

Community
  • 1
  • 1
Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
0

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

Cerbrus
  • 70,800
  • 18
  • 132
  • 147