var n = 10000;
var arr = new Array(n);
for (var i = 0; i < n; i++) {
arr[i] = i;
}
var n = 10000;
var arr = [];
for (var i = 0; i < n; i++) {
arr.push(i);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array constructor - 10000 items | |
Array literal - 10000 items |
Test name | Executions per second |
---|---|
Array constructor - 10000 items | 20529.8 Ops/sec |
Array literal - 10000 items | 17718.3 Ops/sec |
Let's break down what is being tested in the provided JSON.
Benchmark Definition The benchmark definition is a simple JavaScript microbenchmark that compares two approaches to create an array:
new Array()
syntax to create an empty array and then populating it with values using a loop.[]
to create an empty array and then populating it with values using the push()
method.Options Compared The two options are being compared:
new Array(n)
and then populating it with values using a loop.[]
and then populating it with values using the push()
method.Pros and Cons
push()
method, which has to search for the end of the array to add new elements. However, it also requires creating a new object and allocating memory, which can be slower in some cases.push()
method.Library Used
In this benchmark, there is no specific library being used. The only library that might be implicitly included is the JavaScript standard library, which provides the Array
prototype and other built-in functionality.
Special JS Feature or Syntax There are no special JavaScript features or syntaxes being tested in this benchmark. It's a straightforward comparison of two basic array creation approaches.
Other Alternatives In terms of alternative ways to create arrays, there are a few:
Array.from()
method: This method was introduced in ECMAScript 2015 (ES6) and allows creating an array from an iterable or an array-like object.concat()
method: This method can be used to concatenate two or more arrays, but it's not suitable for creating a new array from scratch.It's worth noting that the choice of array creation approach can depend on specific use cases and performance requirements. For example, if you need to create an array with a fixed size, using new Array(n)
might be faster than using []
and push()
. However, if you're working with dynamic data or need to concatenate multiple arrays, Array.from()
or the spread operator (...
) might be more suitable.