<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var obj = {
a: 1,
b: 2,
c: 3,
}
_.forOwn(obj, (a) => {console.log(a)});
Object.keys(obj).forEach((a) => {console.log(a)});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash forOwn | |
Keys and then forEach |
Test name | Executions per second |
---|---|
lodash forOwn | 18309.7 Ops/sec |
Keys and then forEach | 20243.3 Ops/sec |
I'll break down the benchmark definition and test cases to explain what's being tested, compared, and their pros and cons.
Benchmark Definition
The benchmark measures two different approaches for iterating over an object's keys: using Lodash's forOwn
method versus native JavaScript's Object.keys()
and forEach
methods.
Script Preparation Code
The script preparation code creates a simple object obj
with three properties (a
, b
, and c
) initialized with values 1, 2, and 3, respectively.
Html Preparation Code
The HTML preparation code includes a reference to the Lodash JavaScript library (version 4.17.5) in the <script>
tag, which will be used by the test cases.
Test Cases
There are two individual test cases:
forOwn
method to iterate over the object's keys. The _.forOwn(obj, (a) => {console.log(a)})
expression calls a callback function with each key as an argument.Object.keys()
method and then applies the forEach
method to print each key.Comparison
The benchmark compares the execution performance of these two approaches on Firefox 81 browser, running on a desktop platform with Windows operating system. The measurements are reported in executions per second (ExecutionsPerSecond).
Pros and Cons:
Library:
The lodash
library is a popular JavaScript utility library that provides various functional programming helpers. In this benchmark, it's used to implement the forOwn
method.
Special JS Feature/Syntax:
None mentioned in the provided benchmark definition.
Alternatives:
Other approaches for iterating over object keys might include:
forEach
with a custom callback function without Lodash (as done in the second test case).Keep in mind that this benchmark primarily compares two specific approaches and might not cover all possible use cases or optimization strategies for object key iteration.