<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));
const has = Object.prototype.hasOwnProperty;
const props = [
"type",
"subtype",
"card_last4",
"card_type",
"card_exp_month",
"card_exp_year",
"card_country",
"something"
];
function pick(element, props) {
const res = {};
for (const prop of props) {
if (has.call(element, prop)) res[prop] = element[prop];
}
return res;
}
arr.map((element) => pick(element, props));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash | |
compiled pick function | |
loop |
Test name | Executions per second |
---|---|
Lodash | 3.8 Ops/sec |
compiled pick function | 60.7 Ops/sec |
loop | 25.1 Ops/sec |
Let's break down the benchmark and its test cases.
Benchmark Purpose: The benchmark is designed to compare three different approaches for extracting specific properties from an object in JavaScript:
pick
functionLodash pick
Function:
The Lodash pick
function is used to extract specific properties from an object. It takes an array of property names as input and returns an object with only the specified properties.
Pros:
pick
function provides a simple and concise way to extract properties.Cons:
pick
function, you have limited control over the generated code.Compiled Pick Function: The compiled pick function is a custom implementation that generates a dynamic property extraction code. This approach allows for more control over the generated code but requires manual effort to set up.
Pros:
Cons:
Loop-Based Approach: The loop-based approach involves manually iterating through the properties of interest in the object and assigning their values to a new object.
Pros:
Cons:
Other Considerations:
Alternatives: Some alternative approaches to consider include:
Object.fromEntries()
or Object.entries()
instead of a loop-based approach for picking properties.pick
function with other object extraction libraries or built-in JavaScript methods.I hope this explanation helps you understand the benchmark and its test cases!