function test1(array) {
for (let i = 0; i < array.length; i++) {
let lsum = array.slice(0, i).reduce((carry, value) => carry + value, 0);
let rsum = array.slice(i).reduce((carry, value) => carry + value, 0);
if (lsum === rsum) return i;
}
return -1;
}
function test2(array) {
let sum = array.reduce((carry, value) => carry + value, 0);
for (let i = 0, lsum = 0, rsum = sum; i < array.length; i++, lsum += array[i - 1], rsum -= array[i - 1]) {
if (lsum === rsum) {
return i;
}
}
return -1;
}
test1([1, 5, -8, 0, -2]);
test1([-2, 2, 5]);
test1([1, 1, 1, 1, -4]);
test2([1, 5, -8, 0, -2]);
test2([-2, 2, 5]);
test2([1, 1, 1, 1, -4]);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
function 1 | |
function 2 |
Test name | Executions per second |
---|---|
function 1 | 428923.5 Ops/sec |
function 2 | 2408855.2 Ops/sec |
Let's break down the provided benchmark and its various components.
Benchmark Definition:
The benchmark is defined by two JavaScript functions, test1
and test2
. Both functions take an array as input and are expected to find the middle element(s) of the array. The difference between these two functions lies in their approach:
test1
: This function iterates through the array, calculates the sum of elements on both sides of each index (i
), and checks if they're equal. If a match is found, it returns the current index; otherwise, it returns -1
.test2
: This function first calculates the total sum of all elements in the array using the reduce()
method. Then, it iterates through the array again, maintaining two running sums: lsum
(left side) and rsum
(right side). It checks if lsum
equals rsum
, returning the current index when a match is found; otherwise, it continues to the next iteration.Comparison of Options:
The benchmark allows for comparison between different JavaScript implementations. The options being compared are:
test2
uses a sum-based approach, which calculates the total sum of all elements first and then iterates through the array to find the middle element.Pros and Cons:
Library Usage:
Neither test1
nor test2
uses any external libraries, so there's no library-specific implementation or optimization involved in these benchmark cases.
Special JS Features/Syntax: There are a few features used in this benchmark:
reduce()
: This method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.=>
): Used for concise function definitions.Other Alternatives: If you're looking to optimize or implement similar benchmarks, consider exploring other approaches:
Array.prototype.indexOf()
instead of manual iteration).These alternatives can help you optimize or implement similar benchmarks more efficiently.