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);
}
function includesNative(array, item) {
return array.includes(item);
}
forLoop(arr, 'donuts')
whileLoop(arr, 'donuts')
indexOfNative(arr, 'donuts')
forLoop(arr, 'yogurt')
whileLoop(arr, 'yogurt')
indexOfNative(arr, 'yogurt')
includesNative(arr, 'donuts')
includesNative(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 | |
includes for item towards start | |
includes for item towards end |
Test name | Executions per second |
---|---|
For Loop for item towards beginning | 103348544.0 Ops/sec |
While Loop for item towards beginning | 113800144.0 Ops/sec |
indexOf for item towards beginning | 83591016.0 Ops/sec |
For Loop for item towards end | 47705156.0 Ops/sec |
While Loop for item towards end | 45000556.0 Ops/sec |
indexOf for item towards end | 36180668.0 Ops/sec |
includes for item towards start | 82337216.0 Ops/sec |
includes for item towards end | 37468276.0 Ops/sec |
I'll break down the provided benchmark and explain what's being tested, compared, and the pros and cons of each approach.
Benchmark Overview
The benchmark measures the performance of three different approaches to find an item in an array:
Each test case uses a specific input array (arr
) with multiple items, and a target item to search for. The benchmark is executed on Firefox 131 on a desktop platform.
Approaches Compared
for
loop, checking each element to see if it matches the target item.while
loop instead.Pros and Cons
Library and Special Features
None mentioned in this benchmark.
Other Alternatives
In summary, this benchmark compares the performance of four different approaches to find an item in an array: For Loop, While Loop, indexOf (native JavaScript function), and includes (native JavaScript function). The results will help determine which approach is fastest and most efficient.