I want to create an array in javascript and remember two ways of doing it so I just want to know what the fundamental differences are and if there is a performance differenc
They do the same thing. Advantages to the []
notation are:
Array
symbol, it still works.new Array(3)
, if you're used to seeing entries listed in the constructor, you could easily misread that to mean [3]
, when in fact it creates a new array with a length
of 3 and no entries.new Array
, the interpreter has to go look up the Array
symbol, which means traversing all entries in the scope chain until it gets to the global object and finds it, whereas with []
it doesn't need to do that. The odds of that having any tangible real-world impact in normal use cases are low. Still, though...So there are several good reasons to use []
.
Advantages to new Array
:
var a = new Array(3);
I haven't had any reason to do that in several years (not since learning that arrays aren't really arrays and there's no point trying to pre-allocate them). And if you really want to, you can always do this:
var a = [];
a.length = 3;
There's no difference in your usage.
The only real usage difference is passing an integer parameter to new Array()
which will set an initial array length (which you can't do with the []
array-literal notation). But they create identical objects either way in your use case.
I think both ways are the same in terms of performance since they both create an "Array object" eventually. So once you start accessing the array the mechanism will be the same. I not too sure about how different the mechanisms to construct the arrays be (in terms of performance) though it shouldn't be any noticeable gains using one way to the other.
I believe the performance benefits are negligible.
See http://jsperf.com/new-array-vs-literal-array/4
This benchmark on JSPerf shows the array literal form to be generally faster than the constructor on some browsers (and not slower on any).
This behavior is, of course, totally implementation dependent, so you'll need to run your own test on your own target platforms.