var list = Array.from({ length: 1000 }).map((_, i) => `Item ${i + 1}`);
var newList = [];
list.forEach(item => newList.push(item));
var newList = [];
list.forEach(item => newList = [ newList, item ]);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
A: push | |
B: Spread |
Test name | Executions per second |
---|---|
A: push | 119916.5 Ops/sec |
B: Spread | 3000.5 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net!
The provided benchmark measures the performance difference between two approaches to add elements to an array in JavaScript:
Array.prototype.push()
...
) with assignment (newList = [ ...newList, item ]
)Options compared:
...
) in older browsers and Node.js versions.Other considerations:
Array.prototype.splice()
: While not directly related to adding elements at the end of an array, splice()
is often used for inserting elements, which can lead to similar performance issues as pushing.Library and special JS feature:
There's no specific library or advanced JavaScript feature mentioned in this benchmark. The focus is on comparing two basic approaches to manipulate arrays in JavaScript.
Explanation of the spread operator (...
):
The spread operator is a relatively new addition to the JavaScript language, introduced in ECMAScript 2015 (ES6). It allows you to expand an array or other iterable into individual elements, which can be used as arguments for a function or assigned to a new variable. In this benchmark, the spread operator is used with assignment (newList = [ ...newList, item ];
) to create a new array by appending item
to the existing newList
.
Benchmark preparation code:
The script preparation code creates an array list
with 1000 elements using Array.from()
and map()
. This is done to provide a common starting point for both test cases.
Individual test cases:
There are two individual test cases:
newList
and uses forEach()
to push each element from list
onto newList
.newList
and uses forEach()
to assign each element from list
to newList
, using the spread operator with assignment.Latest benchmark result:
The latest results show that Chrome 81 on Desktop (Mac OS X 10.14.6) executes push approximately 67423 times per second, while executing spread approximately 1527 times per second. This suggests that push is currently faster than the spread approach in this specific test case.
Keep in mind that benchmark results may vary depending on the specific environment and browser version used.
Other alternatives:
If you're looking for alternative approaches to adding elements to an array, consider:
push()
or the spread operator.Array.prototype.splice()
: Inserting or replacing elements in an array using splice()
, which can lead to similar performance issues as pushing.However, these alternatives are generally slower than using push
or the spread operator.