<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>
var arr = [];
var object = {
type: 'aaa',
subtype: 'bbb',
card_last4:'bbb',
card_type:'bbb',
card_exp_month:'bbb',
card_exp_year:'bbb',
card_country:'bbb',
foo: 'bar'
};
for (var i = 0; i <= 100000; i++) { arr.push(object); }
arr.map(function (element) {
return _.pick(
element,
'type',
'subtype',
'card_last4',
'card_type',
'card_exp_month',
'card_exp_year',
'card_country',
'something'
);
});
const props = [
"type",
"subtype",
"card_last4",
"card_type",
"card_exp_month",
"card_exp_year",
"card_country",
"something"
];
function pickBuilder(props) {
const obj = props.map((prop) => `if (has.call(el, '${prop}')) res.${prop} = el.${prop}`).join(';');
return new Function('el', `const has = Object.prototype.hasOwnProperty; const res = {}; ${obj}; return res;`);
}
const pick = pickBuilder(props)
arr.map((element) => pick(element));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash | |
compiled pick function |
Test name | Executions per second |
---|---|
Lodash | 2.9 Ops/sec |
compiled pick function | 36.8 Ops/sec |
I'll break down the provided benchmark definition and test cases to explain what's being tested, the options compared, their pros and cons, and other considerations.
Benchmark Definition
The benchmark is testing two approaches for picking specific properties from an object: using Lodash's pick
function versus a compiled version of a pick function.
Options Compared
pick
function: The official JavaScript utility library Lodash provides a pick
function that takes an object, an array of keys to pick, and returns a new object with only the specified properties.Function
constructor to create a new function that performs the picking.Pros and Cons
Lodash's pick
function:
Pros:
Cons:
Compiled pick function:
Pros:
pick
function if optimized correctlyCons:
Other Considerations
100000
) to simulate real-world performance scenarios.Library Used: Lodash
Lodash is a popular JavaScript utility library that provides a wide range of functions for various tasks, including data manipulation, string manipulation, and more. In this case, the pick
function is used to select specific properties from an object.
Special JS Feature/Syntax
None mentioned in the provided benchmark definition. However, it's worth noting that the compiled pick function uses some advanced JavaScript features like template literals, Function
constructor, and has.call()
method, which might be less familiar to developers without experience with these concepts.
Alternatives
Other alternatives for picking properties from an object include:
Object.prototype.hasOwnProperty()
Object.entries()
methodKeep in mind that these alternatives might not be as convenient or performant as Lodash's pick
function or the compiled pick function.