const sum = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9;
function getSum(args) {
return args.reduce((a, b) => a + b, 0);
}
const sum = getSum(1, 2, 3, 4, 5, 6, 7, 8, 9);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
builtin plus operator | |
custom sum method |
Test name | Executions per second |
---|---|
builtin plus operator | 1411770368.0 Ops/sec |
custom sum method | 112532832.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Definition
The benchmark is defined by providing a Script Preparation Code
and an optional Html Preparation Code
. However, in this case, both fields are empty, indicating that the script preparation code will be generated automatically by the browser. The benchmark definition also specifies two test cases: "builtin plus operator" and "custom sum method".
Test Cases The test cases compare the performance of two approaches to calculate the sum of an array:
+
operator to add all numbers in the array.getSum
, which uses the reduce()
method to add all numbers in the array.Options Compared The benchmark compares the performance of these two approaches:
+
operator to add all numbers in the array.getSum
, which uses the reduce()
method to add all numbers in the array.Pros and Cons
Library and Syntax
There is no specific library mentioned in the benchmark definition. However, the custom sum method uses the reduce()
method, which is a part of the ECMAScript standard.
Special JS Feature or Syntax
The custom sum method uses the function
keyword to define a new function, getSum
, and the =>
syntax for arrow functions (introduced in ECMAScript 2015). The reduce()
method is also a part of the ECMAScript standard.
Other Alternatives
There are other ways to calculate the sum of an array in JavaScript, such as using a for
loop or the Array.prototype.reduce()
method with a callback function. Some examples include:
for
loop: let sum = 0; for (let i = 0; i < arr.length; i++) { sum += arr[i]; }
Array.prototype.reduce()
: arr.reduce((a, b) => a + b, 0)
map()
and reduce()
: arr.map(x => x).reduce((a, b) => a + b, 0)
Keep in mind that the performance differences between these approaches may vary depending on the specific use case and browser implementation.