<script src="https://cdn.jsdelivr.net/lodash/4.16.0/lodash.min.js"></script>
var values = {a: 123, b: 234, c: 445, d: 23, e: 234, f:234, g: 345, h: 34, i: 43};
var forEachObjectKey = (object, toRun) => {
const keys = Object.keys(object)
let length = keys.length
let index = -1
while (length--) {
index++
toRun(keys[index], (object)[keys[index]])
}
}
let count = 0;
_.forEach(values, (v,i) => {
if (i != null) {
count+= i;
}
})
let count = 0
forEachObjectKey(values, (key, value) => {
if (value != null) {
count += value
}
})
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash.forEach | |
custom foreach |
Test name | Executions per second |
---|---|
lodash.forEach | 4001531.8 Ops/sec |
custom foreach | 9230919.0 Ops/sec |
Let's dive into explaining the provided benchmark.
Benchmark Overview
The provided benchmark compares two approaches to iterating over object keys: using Lodash's forEach
function and a custom implementation.
Comparison Options
The benchmark tests two options:
forEach
function: This option uses Lodash's forEach
function, which is a utility function that iterates over arrays or objects.Object.keys()
, length
, and while
loops.Pros and Cons
Here are some pros and cons of each approach:
forEach
function:Library: Lodash
Lodash is a popular JavaScript utility library that provides a wide range of functions for tasks such as array manipulation, string manipulation, object manipulation, and more. The forEach
function in this benchmark is part of the Lodash library, which iterates over arrays or objects and executes a provided callback function on each element.
Special JS Feature: Async/await
The custom implementation uses async/await syntax to handle the iteration logic. This allows for cleaner and easier-to-read code, but may also introduce additional complexity due to the use of asynchronous programming.
Benchmark Preparation Code
The benchmark preparation code defines two variables: values
(an object with string keys) and forEachObjectKey
(the custom implementation function). The forEachObjectKey
function iterates over the object's keys using Object.keys()
and executes a callback function on each key-value pair.
Latest Benchmark Result
The latest benchmark result shows that the custom implementation outperforms Lodash's forEach
function, with approximately 290% more executions per second. However, it's essential to note that this may be due to various factors such as the specific hardware architecture, browser version, and testing environment used in the benchmark.
Other Alternatives
If you're looking for alternatives to Lodash or custom implementations, here are a few options:
Array.forEach()
: Modern JavaScript engines like V8 (used by Chrome) provide an optimized implementation of forEach()
that can be used as an alternative.Array.prototype.forEach()
or Object.keys()
, which can be used as alternatives to Lodash's forEach
function.