var data = Array.from({length: 10000}, () => Math.floor(Math.random() * 1000));
let sum = 0;
for (let i=0; i < data.length; i++){
sum += data[i];
}
let sum = 0;
for (const n of data){
sum += n;
}
for (let i=0; i < data.length; i++){
}
for (const n of data){
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
1 | |
2 | |
3 | |
4 |
Test name | Executions per second |
---|---|
1 | 503.8 Ops/sec |
2 | 63511.1 Ops/sec |
3 | 985.9 Ops/sec |
4 | 90941.2 Ops/sec |
Let's break down the benchmark definition and test cases.
Benchmark Definition
The provided JSON represents a JavaScript microbenchmark named "For vs For of loop v3". The script preparation code initializes an array data
with 10,000 random integers between 0 and 1000 using Array.from()
. This creates a large dataset that will be used to test the performance of different loop constructs.
Script Preparation Code
var data = Array.from({length: 10000}, () => Math.floor(Math.random() * 1000));
This code generates an array of 10,000 random integers using Array.from()
and assigns it to the data
variable.
Html Preparation Code Since there is no HTML preparation code, we can assume that the benchmark will be executed in a headless browser environment or a Node.js environment without a GUI.
Test Cases There are four test cases:
for
loop with an index variable (i
):let sum = 0;
for (let i=0; i < data.length; i++) {
sum += data[i];
}
for...of
loop construct to iterate over the array:let sum = 0;
for (const n of data) {
sum += n;
}
for
loop without an index variable (i
):for (let i=0; i < data.length; i++) {
// empty loop body
}
for...of
loop construct to iterate over the array:for (const n of data) {
// empty loop body
}
Options Compared
The benchmark compares the performance of two loop constructs:
for
loops with and without an index variable (i
).for...of
loop construct, which was introduced in ECMAScript 2015.Pros and Cons
for
loops: Pros:for...of
loop construct: Pros:Library Used (if applicable)
None of the test cases use a specific library. However, if we consider the for...of
loop construct, it's worth noting that this feature is part of the ECMAScript standard and has built-in support in most modern JavaScript engines.
Special JS Feature or Syntax (if applicable)
The for...of
loop construct was introduced in ECMAScript 2015 and is a new syntax for iterating over arrays and other iterables. This feature was added to provide a more concise and expressive way of working with iterables, making it easier to write efficient and readable code.
Alternatives
If you're interested in exploring alternative approaches, here are some options:
while
loops or for-in
loops.lodash
or underscore
that provide utility functions for iteration and array manipulation.Keep in mind that the choice of loop construct ultimately depends on the specific requirements and constraints of your project.