a = [];
for(var i=0;i<10000;i++){
a.push({index:i,data:"blabla",randomField:"foobarfoobarfoobarfoobar",date:Date.now()});
}
var indexToFind = 5780;
ind = -1;
for(var i =0;i<a.length;i++){
if(a[i].index == indexToFind){
ind = i;
}
}
a[ind].data;
a.find(x => x.index == indexToFind).data;
a.find(function(cv,i){ return cv.index == indexToFind;}).data;
a.find(function(cv,i){
if(cv.index == indexToFind){
ind = i;
return true;
}else
return false;
}).data;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for loop | |
javascript array.find | |
javascript array.find with function | |
javascript array.find with function and index |
Test name | Executions per second |
---|---|
for loop | 548.6 Ops/sec |
javascript array.find | 4168.9 Ops/sec |
javascript array.find with function | 4167.5 Ops/sec |
javascript array.find with function and index | 4219.5 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Definition
The benchmark defines an array a
with 10,000 elements, each containing an index
, data
, and randomField
. The date
field is set to the current time. We're interested in finding the element at a specific index (5780
) using different approaches: for loops, Array.prototype.find()
, and variations of the latter.
Options Compared
The benchmark compares four options:
true
when the element is found.ind
) with the index of the found element.Pros and Cons
Here's a brief summary of each approach:
find()
method alone, but still relatively efficient.find()
. However, be cautious about using external variables in this context.Library Usage
None of the benchmark options rely on any specific libraries. They are all pure JavaScript implementations.
Special JS Features
The benchmark doesn't explicitly mention any special JavaScript features like let
/const
, arrow functions, or ES6 classes. However, it does use traditional for loops and function definitions, which might be less efficient than their modern counterparts.
Benchmark Preparation Code
The preparation code creates an array of 10,000 elements with specific properties and values. The indexToFind
variable is set to a specific value (5780) that will be used in the benchmark tests.
Now that we've explored the benchmark definition, let's move on to some alternative approaches:
Other Alternatives
Some possible alternative approaches for finding an element in an array include:
Array.prototype.findIndex()
instead of find()
, which returns -1 if no element is found.Keep in mind that each approach has its trade-offs and might be more suitable for specific use cases.