var array = new Array(1000);
for (var i = 0; i < array.length; i++) {
array[i];
}
array.forEach(function(i) {
array[i];
});
array.some(function(i) {
array[i];
});
for (var i of array) {
array[i];
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
foreach | |
some | |
for..of |
Test name | Executions per second |
---|---|
for | 1504004.5 Ops/sec |
foreach | 905614.1 Ops/sec |
some | 915151.3 Ops/sec |
for..of | 109650.2 Ops/sec |
Let's break down the test cases and explain what is being tested, along with the pros and cons of each approach.
Test Case: Loops - For vs Foreach vs Some vs For..of
The goal of this benchmark is to compare the performance of different loop constructs in JavaScript:
break
statement in other languages.Pros and Cons:
break
statement in other languages.Library Usage
The benchmark uses the built-in JavaScript array functions without any external libraries. However, it's worth noting that if you were to use a library like Lodash, which provides more functional programming constructs, you might see different performance results.
Special JS Features/Syntax
This benchmark does not explicitly test any special features or syntax in JavaScript, but the for..of loop is a relatively new feature introduced in ECMAScript 2015 (ES6). The for..of loop is designed to iterate over arrays and other iterable objects using an iterator protocol. It's similar to a traditional for
loop but provides more convenience and safety features.
Alternative Benchmarks
If you wanted to benchmark different aspects of loops, here are some alternative approaches:
array[i]
) versus using an iterator or a for loop.Buffer
or Uint8Array
) versus managed memory allocation (e.g., using new Int32Array()
).