const text = new Array(2000000).fill("a").join("");
const text = new Array(2000000).fill("a").join("");
const string = new Array(text.length);
for (let i = 0; i < text.length; i++) {
string[i] = text[i];
}
const text = new Array(2000000).fill("a").join("");
const string = [];
for (const char of text) {
string.push(char);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
for ... of |
Test name | Executions per second |
---|---|
for | 24.1 Ops/sec |
for ... of | 15.8 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net!
What is tested?
The provided benchmark measures the performance difference between two approaches to iterate over an array in JavaScript:
for
loop: This involves using the traditional syntax for a for
loop, where you declare a variable, initialize it, and then use it to control the loop.for ... of
loop: This is a newer syntax introduced in ECMAScript 2015 (ES6) that allows iterating over arrays and other iterable objects using a more concise syntax.Options compared
The benchmark compares the performance of these two approaches:
for
loop: This approach uses a variable to keep track of the current index, increments it, and then checks if it's within the bounds of the array.for ... of
loop: This approach uses the of
keyword to specify the iterable object (in this case, the text
array) and automatically increments the iteration variable.Pros and Cons
Here are some pros and cons for each approach:
for
loopPros:
Cons:
for ... of
loopPros:
Cons:
of
keywordLibrary usage
In this benchmark, a library is not explicitly mentioned. However, it's likely that the arrays are created using the built-in JavaScript Array
constructor.
Special JS feature or syntax
The benchmark uses a newer syntax introduced in ES6: the for ... of
loop. This is a relatively recent addition to the language and provides a concise way to iterate over arrays and other iterable objects.
Other alternatives
If you were to write this benchmark from scratch, you might consider alternative approaches, such as:
forEach()
or map()
: These methods provide a more functional programming style and can be faster for small iterations.reduce()
: This method provides a way to iterate over arrays and accumulate values, but may have higher overhead due to the need to manage state.Keep in mind that each approach has its own trade-offs and may not be suitable for every scenario.