const arr = Array(10000).fill(0);
const l = arr.length;
for (let i = 0; i < l; i++) {
arr[i];
}
const arr = Array(10000).fill(0);
for (let x of arr) {
x;
}
const arr = Array(10000).fill(0);
for (let i in arr) {
arr[i];
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
for of | |
for in |
Test name | Executions per second |
---|---|
for | 69507.0 Ops/sec |
for of | 59764.8 Ops/sec |
for in | 4721.5 Ops/sec |
Overview
MeasureThat.net is a website that allows users to create and run JavaScript microbenchmarks, comparing different approaches for various use cases.
Benchmark Definition
The provided JSON represents the benchmark definition with three test cases:
The script preparation code for each test case is not specified in the JSON, but it's likely that a loop is created to iterate over an array. The HTML preparation code is also empty.
Options Compared
Three options are compared:
Each of these loops has its own pros and cons:
i
). It's generally considered the most readable and maintainable option, but it can be slower due to the overhead of indexing.for
loop) with an iterable object (e.g., arr
). It's concise and often faster than traditional loops because it avoids indexing. However, it may not be suitable for all scenarios or legacy codebases.arr
as if it were an object). It can be slower and less readable than traditional loops due to the overhead of property lookup. However, it's useful when working with objects or arrays with non-standard iteration methods.Library
There is no library explicitly mentioned in the provided JSON, but JavaScript's built-in Array
and String
prototypes use various internal methods for iteration, such as length
, indexOf
, and forEach
.
Special JS Features
The test cases do not explicitly mention any special JavaScript features or syntax, such as:
However, it's worth noting that the For...Of
loop uses a feature introduced in ECMAScript 2015 (ES6).
Alternative Approaches
If you're looking for alternative approaches to these loops, consider the following:
Iterator
interface and next()
method to iterate over objects or arrays.Keep in mind that performance optimizations should always consider the specific use case and requirements of your application.