var arr = [Array(10000)].map((_,i) => i)
arr.forEach((v,i) => {
console.log(v,i);
arr.unshift(arr.splice(i,1).shift())
})
arr.sort((a,b) => (a === b) ? 0 : (a < b) ? 1 : -1)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
unshift | |
swapping |
Test name | Executions per second |
---|---|
unshift | 6.4 Ops/sec |
swapping | 5666.4 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark is comparing two approaches: unshift
and sort
. The goal is to measure their performance, specifically how many times each operation can be executed per second on a given system configuration.
Script Preparation Code
The script preparation code generates an array of 10,000 random numbers using the spread operator (Array(10000)
) and the map()
function. This creates an array that can be modified by the test cases.
Benchmark Definition Json
The benchmark definition json contains two individual test cases:
forEach
loop to iterate over the array, logging each element and its index. Inside the loop, it calls arr.unshift(arr.splice(i, 1).shift())
, which performs an unshift operation on the array.Library and Special JS Feature
The splice()
function used in the unshift
test case is a built-in JavaScript method that modifies the original array by removing elements from their current positions. The .shift()
method is also a built-in method that removes and returns the first element of an array.
Options Compared
Two options are being compared:
arr.unshift()
.sort()
method, which rearranges the elements based on a compare function (in this case, a simple equality check).Pros and Cons
Here's a brief summary of the pros and cons of each approach:
Other Considerations
When evaluating the performance of these two approaches, consider the following factors:
sort
due to its in-place sorting capabilities.unshift
and sort
.unshift
and sort
may vary depending on the system's architecture, compiler optimizations, and available memory.Alternatives
If you need to benchmark other approaches for inserting or sorting elements in an array, consider exploring these alternatives:
unshift
, which inserts an element at a specific index.slice()
to extract the elements you want to keep and then concatenate them with another array created using concat()
.