window.top.tests = {control:[], concat:[], spread:[]};
window.test = (new Array(10)).fill(null);
window.cutoff = 5000;
for (let element of window.test) window.top.tests.control.push(element);
if (window.top.tests.control.length > window.cutoff) { window.top.tests.control = []; console.log('reset control'); }
window.top.tests.concat = window.top.tests.concat.concat(window.test);
if (window.top.tests.concat.length > window.cutoff) { window.top.tests.concat = []; console.log('reset concat'); }
window.top.tests.spread.push(window.test);
if (window.top.tests.spread.length > window.cutoff) { window.top.tests.spread = []; console.log('reset spread'); }
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Control (for push) | |
Concat | |
Spread |
Test name | Executions per second |
---|---|
Control (for push) | 1005382.9 Ops/sec |
Concat | 1510156.6 Ops/sec |
Spread | 4650735.5 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares three approaches to appending to a large array in JavaScript:
push()
method (Control)concat()
method (Concat)...
) (Spread)These tests aim to determine which approach is the fastest and most efficient for large arrays.
Library and Purpose
In this benchmark, two libraries/libraries are used:
Special JS Feature/Syntax
The benchmark uses the spread syntax (...
) to append elements to an array. The spread syntax was introduced in ECMAScript 2015 (ES6) and allows for creating a new array by spreading the elements of an existing array or an array-like object.
Benchmark Test Cases
Each test case is defined as follows:
window.top.tests.control.push(element);
: This line appends an element to the end of the control
array using the push()
method.window.top.tests.concat = window.top.tests.concat.concat(window.test);
: This line appends all elements from the test
array to the end of the concat
array using the concat()
method.window.top.tests.spread.push(...window.test);
: This line appends all elements from the test
array to the end of the spread
array using the spread syntax (...
).Options Being Compared
The benchmark compares the performance of each approach for large arrays:
Pros and Cons of Each Approach
Here's a brief overview of the pros and cons of each approach:
concat()
with an array-like object).Other Considerations
When choosing an approach, consider the following factors:
Alternatives
Other alternatives for appending elements to an array include:
unshift()
: Adds an element to the beginning of an array, which can be useful for inserting new elements at a specific position.splice()
: Removes and replaces elements in an array, which can be useful for inserting or removing elements at specific positions.However, these alternatives may not offer the same level of efficiency or convenience as push(), concat(), or spread().