Creating an array of size n in O(1) time is theoretically possible depending on implementation details - in principle, if an array is implemented as a hashtable then its length
property can be set without allocating or initialising space for all of its elements. The ECMAScript specification for the Array(n)
constructor doesn't mandate that Array(n)
should do anything which necessarily takes more than O(1) time, although it also doesn't mandate that the time complexity is O(1).
In practice, Array(n)
's time complexity depends on the browser, though verifying this is a bit tricky. The performance.now()
function can be used to measure the time elapsed between the start and end of a computation, but the precision of this function is artificially reduced in many browsers to protect against CPU-timing attacks like Spectre. To get around this, we can call the constructor repetitions
times, and then divide the time elapsed by repetitions
to get a more precise measurement per constructor call.
My timing code is below:
function timeArray(n, repetitions=100000) {
var startTime = performance.now();
for(var i = 0; i < repetitions; ++i) {
var arr = Array(n);
arr[n-1] = 'foo';
}
var endTime = performance.now();
return (endTime - startTime) / repetitions;
}
for(var n = 10000; n <= 1000000; n += 10000) {
console.log(n, timeArray(n));
}
Here's my results from Google Chrome (version 74) and Firefox (version 72); on Chrome the performance is clearly O(n) and on Firefox it's clearly O(1) with a quite consistent time of about 0.01ms on my machine.

I measured using repetitions = 1000
on Chrome, and repetitions = 100000
on Firefox, to get accurate enough results within a reasonable time.
Another option proposed by @M.Dietz in the comments is to declare the array like var arr = [];
and then assign at some index (e.g. arr[n-1] = 'foo';
). This turns out to take O(1) time on both Chrome and Firefox, both consistently under one nanosecond:

That suggests the version using []
is better to use than the version using Array(n)
, but still the specification doesn't mandate that this should take O(1) time, so there may be other browsers where this version takes O(n) time. If anybody gets different results on another browser (or another version of one of these browsers) then please do add a comment.