var arr = [11, 22, 33, 44, 55, 66, 77, 88, 99, 111, 222, 333, 444, 555, 666, 777, 888, 999];
arr.push(1000);
arr = [arr, 1000];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Push to array Test | |
Spread Test |
Test name | Executions per second |
---|---|
Push to array Test | 5199428.5 Ops/sec |
Spread Test | 3.2 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
What is tested?
The provided JSON represents two test cases, each measuring the performance difference between two approaches: using the push()
method and using the spread operator (...
) to add an element to an array.
Options compared:
arr.push(1000);
: This approach uses the push()
method to add a new element to the end of the array.arr = [...arr, 1000];
: This approach uses the spread operator (...
) to create a new array with the original elements and then adds the new element.Pros and Cons:
push()
method:...
):However, the spread operator's performance advantage over push()
is often negligible unless dealing with extremely large datasets. In reality, both approaches have similar performance characteristics in most cases.
Library and purpose:
None of the provided test cases use a JavaScript library.
Special JS feature or syntax:
The spread operator (...
) was introduced in ECMAScript 2015 (ES6) and is now widely supported by modern browsers. It's a convenient way to create a new array by copying elements from an existing array or other iterable.
Benchmark preparation code explanation:
The provided Script Preparation Code
section initializes an array arr
with 22 elements, which will be used as the base for both test cases.
Other alternatives:
There are two other common ways to add an element to an array:
concat()
: This approach uses the concat()
method to create a new array by concatenating the original array with the new element.set()
: This approach uses the set()
method (available in modern browsers) to add a single element to the end of the array.MeasureThat.net already includes tests for these alternative approaches, which can be found in their benchmark catalog.
In summary, the two test cases compare the performance of adding an element to an array using the push()
method and the spread operator (...
). While both approaches have similar performance characteristics, the spread operator is often preferred due to its readability advantages.