var arr = new Array(500).fill().map(()=>({id:Math.random()**Math.random()**Math.random()}));
const res1=arr.map(({id})=>id>Math.random()?{foo:'bar'}:{bar:'foo'});
const res2=new Array(arr.length);
for (let i=arr.length-1;i>-1;i--){
res2[i]=arr[i].id>Math.random()?{foo:'bar'}:{bar:'foo'}
}
const res2=new Array(arr.length);
for (let i=0;i<arr.length;i++){
res2[i]=arr[i].id>Math.random()?{foo:'bar'}:{bar:'foo'}
}
const res2=[]
for (let i=0;i<arr.length;i++){
res2.push(arr[i].id>Math.random()?{foo:'bar'}:{bar:'foo'})
}
const res2=new Array();
for (let i=arr.length-1;i>-1;i--){
res2.unshift(arr[i].id>Math.random()?{foo:'bar'}:{bar:'foo'})
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
map | |
reverse for | |
for | |
for push | |
reverse for unshift |
Test name | Executions per second |
---|---|
map | 37545.5 Ops/sec |
reverse for | 25309.4 Ops/sec |
for | 19245.6 Ops/sec |
for push | 19035.5 Ops/sec |
reverse for unshift | 19034.5 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
Benchmark Definition
The benchmark is designed to compare the performance of four different approaches: map()
, for
loop, push()
array method, and unshift()
array method on an array of 500 objects. The benchmark is repeated for each approach, allowing users to compare their relative performance.
Options Compared
Array.prototype.map()
method to create a new array with transformed elements.for
loop to iterate over the array and apply transformations.Array.prototype.push()
method to add transformed elements to the end of the original array.Array.prototype.unshift()
method to add transformed elements to the beginning of the original array.Pros and Cons of Each Approach
unshift()
.Other Considerations
map()
method creates a new array, while the other approaches modify the original array.for
loop can lead to unexpected results if not controlled carefully.Library/Dependencies
None mentioned in the benchmark definition.
Special JS Features/Syntax
{foo:'bar'}
): Used to create objects with rest parameters.? :
): Used for conditional expressions, such as id>Math.random()?{foo:'bar'}:{bar:'foo'}
.Alternatives
Other approaches to compare in the benchmark could include:
These alternatives would allow users to explore different optimization strategies and gain insights into the performance characteristics of various JavaScript approaches.