var array = ["hello", true, 7];
var newElement = "new";
const newArray = array.toSpliced(array.length, 0, newElement);
const newArray = [array, newElement];
const newArray = array.slice();
newArray.push(newElement);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.toSpliced | |
Spread operator | |
Array.prototype.slice + Array.prototype.push |
Test name | Executions per second |
---|---|
Array.prototype.toSpliced | 7445254.0 Ops/sec |
Spread operator | 12354495.0 Ops/sec |
Array.prototype.slice + Array.prototype.push | 12673347.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
What is being tested?
The provided JSON represents a benchmark test case for cloning and appending an element to an array in JavaScript. Specifically, it compares three approaches:
Array.prototype.toSpliced()
...
)Array.prototype.slice()
with Array.prototype.push()
Options compared:
The three options being compared are designed to achieve the same result - creating a new array and appending an element to it. However, they have different performance characteristics.
toSpliced()
: This method was introduced in ECMAScript 2019 (ES10) as a way to replace the splice()
method for arrays with at most one element being replaced or inserted....
): This is a syntax feature introduced in ECMAScript 2015 (ES6) that allows you to create a new array by copying elements from an existing array.Array.prototype.slice()
with Array.prototype.push()
: This approach involves creating a new array using slice()
and then appending the element using push()
.Pros and Cons of each approach:
toSpliced()
: Pros:...
): Pros:toSpliced()
.
Cons:toSpliced()
for large arrays due to the overhead of creating a new array.Array.prototype.slice()
with Array.prototype.push()
: Pros:toSpliced()
or the spread operator due to the overhead of creating a new array.Library usage:
None of the benchmark test cases use any external libraries.
Special JS feature/syntax:
The spread operator (...
) is a syntax feature introduced in ECMAScript 2015 (ES6). It's not a built-in method, but rather a shorthand way to create a new array by copying elements from an existing array. The toSpliced()
method is a built-in method introduced in ECMAScript 2019 (ES10).
Alternatives:
If you're looking for alternative approaches to cloning and appending an element to an array, consider the following:
Array.from()
: This method creates a new array from an iterable source, which can be used to clone an existing array.Array.push()
with a callback function: This approach involves pushing elements to the end of the array using push()
, but you can provide a callback function that appends the element.Keep in mind that these alternatives may have different performance characteristics compared to the options being tested in the benchmark.