var list = [];
for (var i = 0; i < 10000; i++) {
list.push([0, 0, Math.floor(Math.random() * 100000).toString()]);
}
const result = list.reduce((acc, [, , value]) => {
const valueNum = Number(value);
if (valueNum > acc) {
return valueNum;
}
return acc;
}, 0);
let result = 0;
for (const [, , value] of list) {
const valueNum = Number(value);
if (valueNum > result) {
result = valueNum;
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
reduce | |
for |
Test name | Executions per second |
---|---|
reduce | 490.2 Ops/sec |
for | 514.2 Ops/sec |
Let's break down the benchmark and its options.
Benchmark Overview
The benchmark compares the performance of two approaches to find the maximum value in an array:
Array.prototype.reduce()
method, which applies a callback function to each element in the array, accumulating a result.Script Preparation Code
The script preparation code creates an array of 10,000 elements, where each element is an object containing three properties: [0, 0, string value]
. The string values are generated using Math.random()
and then converted to strings using toString()
. This ensures that the comparison logic only needs to access the numeric part of the value.
Html Preparation Code
There is no HTML preparation code provided, which means this benchmark focuses on JavaScript execution performance without considering DOM-related overhead.
Options Comparison
The two options being compared are:
Array.prototype.reduce()
method, which iterates over the array using a single iteration.Pros and Cons of Each Approach
Reduce Method:
Pros:
Cons:
For Loop Method:
Pros:
Cons:
Library: Array.prototype.reduce()
The Array.prototype.reduce()
method is a built-in JavaScript library that provides an efficient way to iterate over arrays. It applies a callback function to each element, accumulating a result. This library is widely supported across modern browsers and Node.js versions.
Special JS Feature/Syntax:
There are no special JavaScript features or syntax used in this benchmark.
Device Platform and Operating System
The benchmark results were run on an Android device using Opera Mobile 74, which provides insight into how different devices perform under this specific benchmark.
Other Alternatives
Some alternative approaches to finding the maximum value in an array could include:
Math.max()
with a callback function: Array.prototype.map().reduce(Math.max, -Infinity)
Array.prototype.forEach()
and iterating manuallyKeep in mind that these alternatives might not be directly comparable to the original Reduce method or For Loop approach, as they may have different performance characteristics.