var arr = [];
function resetArray(){
for (var i = 0; i < 1000; i++) {
arr[i] = i;
}
}
function someFn(i) {
return i * 3 * 8;
}
resetArray()
resetArray()
var forArray = []
var length = arr.length
for (var i = 0; i < length; i++) {
forArray.push(someFn(arr[i]));
}
resetArray()
var forEachArray = []
arr.forEach(function (item, index){
forEachArray.push(someFn(item));
})
resetArray()
var mapNewArray = [];
mapNewArray = arr.map(function(item){
return someFn(item)
})
resetArray()
var len = arr.length
for (var i = 0; i < len; i++) {
arr[i] = someFn(arr[i]);
}
resetArray()
arr.forEach(function (item, index){
arr[index] = someFn(item);
})
resetArray()
arr = arr.map(function(item, index){
return someFn(item)
})
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for - create new array | |
forEach - create new array | |
map - create new array | |
for - overwrite array | |
forEach - overwrite array | |
map - overwrite array |
Test name | Executions per second |
---|---|
for - create new array | 4517.7 Ops/sec |
forEach - create new array | 5109.1 Ops/sec |
map - create new array | 5560.8 Ops/sec |
for - overwrite array | 3008.4 Ops/sec |
forEach - overwrite array | 3229.8 Ops/sec |
map - overwrite array | 5769.1 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
Benchmark Overview
The provided benchmark compares the performance of three approaches to create and modify arrays: for
loops, forEach
loops, and the map()
method. The test creates an array of 1000 elements and applies a transformation function (someFn
) to each element using each approach.
Options Compared
for
loops to iterate over the array and push or overwrite elements.forEach()
method to iterate over the array and apply a callback function to each element.map()
method to create a new array with transformed elements.Library Used
The benchmark uses the someFn
function, which is defined in the script preparation code:
function someFn(i) {
return i * 3 * 8;
}
This function takes an input value and returns a transformed value. The benchmark applies this transformation to each element of the array using each approach.
Special JS Feature/Syntax
There is no special JavaScript feature or syntax used in this benchmark that requires specific handling or optimization.
Benchmark Results
The latest benchmark results show that:
map()
method is the fastest, with an execution rate of 5769.12 executions per second.for
loops are the slowest, with an average execution rate across all tests.forEach
loops fall in between, with an average execution rate lower than both for
and map
.Other Alternatives
If you're interested in exploring alternative approaches to array iteration, here are a few options:
set
data structures are not typically used for iterating over elements.Keep in mind that the choice of iteration method depends on your specific use case, performance requirements, and personal preference.