var arr = ['apple', 'banana', 'cherry', 'donuts', 'eggplant', 'french fries', 'goulash', 'hamburger', 'ice cream', 'juice', 'kebab', 'lemonade', 'mango', 'nuts', 'octopus', 'parsley', 'quail egg', 'risotto', 'stew', 'tapas', 'udon', 'vanilla', 'wheat', 'xylotil', 'yogurt', 'zucchinni'];
function forLoop(array, item) {
for (var i = 0; i < array.length; i++) {
if (array[i] === item) {
return i;
}
}
return -1;
}
function whileLoop(array, item) {
var i = 0;
while (i < array.length) {
if (array[i] === item) {
return i;
}
i += 1;
}
return -1;
}
function indexOfNative(array, item) {
return array.indexOf(item);
}
forLoop(arr, 'donuts')
whileLoop(arr, 'donuts')
indexOfNative(arr, 'donuts')
forLoop(arr, 'yogurt')
whileLoop(arr, 'yogurt')
indexOfNative(arr, 'yogurt')
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
For Loop for item towards beginning | |
While Loop for item towards beginning | |
indexOf for item towards beginning | |
For Loop for item towards end | |
While Loop for item towards end | |
indexOf for item towards end |
Test name | Executions per second |
---|---|
For Loop for item towards beginning | 105329176.0 Ops/sec |
While Loop for item towards beginning | 102171288.0 Ops/sec |
indexOf for item towards beginning | 91663296.0 Ops/sec |
For Loop for item towards end | 48151336.0 Ops/sec |
While Loop for item towards end | 47881048.0 Ops/sec |
indexOf for item towards end | 35584204.0 Ops/sec |
Let's break down the provided benchmark definition and explain what's being tested.
Benchmark Definition
The benchmark defines three functions:
forLoop(array, item)
: A traditional for
loop that iterates through an array and returns the index of the first occurrence of a specified item.whileLoop(array, item)
: A while
loop that iterates through an array and returns the index of the first occurrence of a specified item.indexOfNative(array, item)
: A native JavaScript function Array.indexOf()
that returns the index of the first occurrence of a specified item in the given array.Options Compared
The benchmark compares the performance of these three functions under two different scenarios:
Pros and Cons
Here's a brief analysis of each approach:
forLoop(array, item)
:whileLoop(array, item)
:for
loop and might have additional overhead due to the loop condition.indexOfNative(array, item)
:Library
The benchmark uses no external libraries besides the standard JavaScript arrays. However, it's worth noting that modern browsers have optimized implementations of Array.indexOf()
under the hood, which might affect the results.
Special JS Feature/Syntax
None mentioned, as this benchmark focuses on a straightforward implementation of loops and indexing.
Alternatives
If you're interested in exploring alternative approaches or optimizing these functions further:
Keep in mind that the choice of implementation and optimization strategies depends on the specific use case and performance requirements.