<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var arr = [];
for(var i = 0; i < 100; i++){
arr.push({a: {b:1}});
}
_.sumBy(arr, (item) => item.a.b)
_.sumBy(arr, ["a", "b"])
_.sumBy(arr, "a.b")
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
sumBy with function | |
sumBy with array | |
sumBy with string |
Test name | Executions per second |
---|---|
sumBy with function | 155274.5 Ops/sec |
sumBy with array | 104002.8 Ops/sec |
sumBy with string | 15407.9 Ops/sec |
Overview of the Benchmark
The provided JSON represents a JavaScript microbenchmark created on MeasureThat.net. The benchmark tests three different approaches to calculate the sum of values in an array using Lodash, a popular utility library for JavaScript.
Benchmark Definition
The benchmark consists of a single script preparation code that creates an array of objects with a nested property a.b
. The HTML preparation code includes the Lodash library version 4.17.5.
Test Cases
There are three individual test cases:
_sumBy
function from Lodash, passing a custom function (item) => item.a.b
as an argument._sumBy
function from Lodash, passing an array [\"a\", \"b\"]
as an argument._sumBy
function from Lodash, passing a string "a.b"
as an argument.Options Compared
The three test cases compare the execution time of the sumBy
function with different approaches:
(item) => item.a.b
[\"a\", \"b\"]
as an argument"a.b"
as an argumentPros and Cons of Each Approach
Here's a brief analysis of each approach:
Lodash Library
Lodash is a utility library that provides a wide range of functions for tasks such as array manipulation, object transformation, and more. In this benchmark, Lodash is used for its _sumBy
function, which calculates the sum of values in an array by applying a provided function to each element.
JavaScript Feature/Syntax
There's no specific JavaScript feature or syntax mentioned in this benchmark that requires special attention.
Alternative Approaches
For calculating the sum of values in an array without using Lodash, developers can use built-in JavaScript methods like reduce()
or forEach()
. However, these approaches might not be as optimized for performance as the ones provided by Lodash.
Here's a basic example using reduce()
:
let arr = [];
for (var i = 0; i < 100; i++) {
arr.push({a: {b:1}});
}
let sum = arr.reduce((acc, item) => acc + item.a.b, 0);
console.log(sum); // Output: the sum of values in the array
Keep in mind that this approach is less optimized for performance compared to using Lodash's _sumBy
function.