var arr = [];
for (let i = 0; i < 100_000; ++i) {
arr.push('i: ' + i);
}
arr.unshift('AddedToFront');
const arr2 = arr;
const arr2 = ['AddedToFront', arr];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
unshift | |
spread |
Test name | Executions per second |
---|---|
unshift | 16298.5 Ops/sec |
spread | 255.3 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares two ways to add elements to an array: using unshift()
or using the spread operator (...
). The test case uses a sample JavaScript array, initialized with 100,000 elements, each containing a string representation of its index. This allows us to measure the performance difference between these two approaches.
Benchmark Definition
The benchmark definition is provided in JSON format and consists of two parts:
arr
and populates it with 100,000 elements using a for
loop.Individual Test Cases
The benchmark consists of two test cases:
unshift()
. It executes the line arr.unshift('AddedToFront');
and assigns the result to a new variable arr2
....
). It executes the line const arr2 = ['AddedToFront', ...arr];
.Library Used
In this benchmark, no specific JavaScript library is explicitly mentioned or used.
Special JS Feature/Syntax
The use of the spread operator (...
) in one of the test cases introduces a modern JavaScript feature that was introduced in ECMAScript 2015 (ES6). This syntax allows for creating new arrays by spreading existing arrays or other iterable objects.
Pros and Cons of Each Approach
...
):unshift()
due to its ability to create a new array without modifying the original one.Other Alternatives
If you wanted to use alternative approaches, you could consider:
unshift()
, you can push elements onto the end of the array and then reverse it.Here's an example:
arr = arr.slice(0, 1).concat(['AddedToFront']);
Keep in mind that these alternatives might have different performance characteristics and may not be as efficient as using unshift()
or the spread operator.
In summary, this benchmark measures the performance difference between two approaches to add elements to an array: using unshift()
versus the spread operator (...
). The use of modern JavaScript features like the spread operator introduces a new dimension to benchmarking and highlights the importance of considering performance characteristics when optimizing code.