<div id='test'></div>
var arr = new Array(2000000).fill('a');
arr.push('b'); //set b as last element
let val;
for(i=0; i<arr.length; i++){
var value = arr[i];
if (value === 'b') {
val = value;
break;
}
}
var arr = new Array(2000000).fill('a');
arr.push('b'); //set b as last element
let val;
for (var value of arr) {
if (value === 'b') {
val = value;
break;
}
}
var arr = new Array(2000000).fill('a');
arr.push('b'); //set b as last element
let val = arr.find(e => e === 'b');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for-loop | |
for..of | |
Array.find() |
Test name | Executions per second |
---|---|
for-loop | 39.6 Ops/sec |
for..of | 26.1 Ops/sec |
Array.find() | 27.6 Ops/sec |
What is being tested?
The provided JSON represents three individual test cases that compare the performance of different approaches for finding an element in a large array: for-loop
, Array.find()
, and for...of
. The test aims to measure which approach is the most efficient.
Options compared:
var i
and arr[i]
.for
loop syntax that allows iterating over arrays using a more concise and expressive way.Pros and Cons:
for-loop
for finding a specific element due to the iteration overhead.Library/Library purpose: None mentioned in this benchmark definition.
Special JS feature/syntax: The Array.find()
method is a built-in JavaScript API introduced in ECMAScript 2019. The For...of
loop syntax is also a modern addition, widely adopted in recent browsers and ECMAScript versions.
Other considerations:
ExecutionsPerSecond
, which suggests that the goal is to find the fastest approach for executing the loop.Alternatives:
Other approaches for finding an element in a large array might include:
arr.filter()
with a callback function can be another way to achieve similar results.Array.prototype.reduce()
could also be explored, although its usage might be more specialized.splice()
and manual indexing might be another alternative.However, these alternatives are less commonly used or may have different performance characteristics compared to the methods tested in this benchmark.