var list = [1, 0, -2, -1, 3, 0, 1, 8, -10, 3, 0, -1, -3];
let countNumberGreaterThanZero = 0;
const listLength = list.length;
for (let i = 0; i < listLength; i++) {
if (list[i] > 0) {
countNumberGreaterThanZero++;
}
}
let countsNumbersGreaterThanZero = (acc, cur) => acc + (cur > 0 ? 1 : 0);
list.reduce(countsNumbersGreaterThanZero, 0)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Number 1: use for iterator | |
Number 2: using reduce method |
Test name | Executions per second |
---|---|
Number 1: use for iterator | 745834.9 Ops/sec |
Number 2: using reduce method | 7007154.5 Ops/sec |
Let's break down the benchmark and explain what's being tested, compared, and their pros and cons.
Benchmark Definition
The benchmark compares two methods to find the quantity of numbers greater than zero in an array:
for
iteration method: A traditional loop-based approach using a for
loop to iterate through the array elements.reduce
method: An array reduction method that applies a callback function to each element, accumulating a result.Script Preparation Code
The script defines an array list
with various numbers:
var list = [1, 0, -2, -1, 3, 0, 1, 8, -10, 3, 0, -1, -3];
This is the input data used for both testing methods.
Individual Test Cases
There are two test cases:
Number 1: use for iterator
The benchmark definition code for this test case uses a traditional for
loop to iterate through the array elements:
let countNumberGreaterThanZero = 0;
const listLength = list.length;
for (let i = 0; i < listLength; i++) {
if (list[i] > 0) {
countNumberGreaterThanZero++;
}
}
This implementation uses a simple loop to iterate through the array elements, incrementing a counter for each element greater than zero.
Number 2: using reduce method
The benchmark definition code for this test case uses the reduce
method with a callback function:
let countsNumbersGreaterThanZero = (acc, cur) => acc + (cur > 0 ? 1 : 0);
list.reduce(countsNumbersGreaterThanZero, 0);
This implementation uses the reduce
method to apply the callback function to each element in the array. The callback function increments an accumulator value (countsNumbersGreaterThanZero
) for each element greater than zero.
Pros and Cons of Each Approach
for
iteration method:reduce
method:Library and Special JS Feature
There is no library used in this benchmark. However, the reduce
method is a built-in JavaScript method that is supported by most modern browsers.
Other Considerations
Alternatives
If you want to compare other approaches or libraries, you can consider:
forEach
, map
, or filter
.Keep in mind that this benchmark is focused on comparing two specific testing methods and may not be representative of all JavaScript scenarios.