var array = new Array(1000);
array.forEach(function(i) {
array[i];
});
for (var i = 0; i < array.length; i++) {
array[i];
}
var length = array.length;
for (var i = 0; i < length; i++) {
array[i];
}
for (var i of array) {
array[i];
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
foreach | |
for | |
for 2 | |
for..of |
Test name | Executions per second |
---|---|
foreach | 464347.3 Ops/sec |
for | 4317.1 Ops/sec |
for 2 | 8648.6 Ops/sec |
for..of | 7228.3 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
Benchmark Definition The benchmark is designed to compare the performance of different loop constructs in JavaScript:
for
foreach
(implemented using an arrow function)some
(not used, likely a leftover from previous versions)for..of
Script Preparation Code
The script creates an array with 1000 elements: var array = new Array(1000);
. This array is used as the data structure for the benchmark.
Options Compared The benchmark compares the performance of four loop constructs:
for
loop: Uses a counter variable to iterate over the array.foreach
loop: Uses the forEach
method with an arrow function to iterate over the array.for
loop with manual length checking: Uses a separate variable to store the length of the array and then uses that variable as the counter.for..of
loop: Uses the for...of
loop syntax, which is a more modern and concise way to iterate over arrays.Pros and Cons
for
loop:foreach
loop:for
loopsforEach
methodfor
loop with manual length checking:length
for..of
loop:for
loopsLibrary
The forEach
method uses the Array prototype's built-in implementation. This method iterates over an array using a callback function, which is executed for each element in the array.
Special JS Feature/Syntax None of the benchmark options use any special JavaScript features or syntax beyond the standard language features mentioned above.
Other Alternatives
If you wanted to add more loop constructs to the benchmark, some alternatives could include:
while
loopsdo...while
loopsmap
, filter
, or reduce
iteratee
functionHowever, these alternatives would likely require significant changes to the benchmark code and might not provide meaningful comparisons with the original options.