<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/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 <= 10; 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'
);
});
function pick(object, keys) {
return keys.reduce((obj, key) => {
if (object && object.hasOwnProperty(key)) {
obj[key] = object[key];
}
return obj;
}, {});
}
arr.map(function (element) {
return pick(
element,
['type',
'subtype',
'card_last4',
'card_type',
'card_exp_month',
'card_exp_year',
'card_country',
'something']
);
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash pick | |
Native pick |
Test name | Executions per second |
---|---|
Lodash pick | 49481.9 Ops/sec |
Native pick | 322780.3 Ops/sec |
Let's break down the provided benchmark and its explanations.
Benchmark Overview
The benchmark tests two approaches for filtering an object using JavaScript:
pick
method: A popular utility library that provides a convenient way to extract specific properties from an object.pick
function: A native implementation of the same functionality, built into modern browsers.Options Compared
The benchmark compares the performance of two options:
pick
methodpick
functionPros and Cons of Each Approach
pick
MethodPros:
Cons:
pick
FunctionPros:
Cons:
Library Description
Lodash is a popular JavaScript utility library that provides a wide range of functions for tasks like array manipulation, object manipulation, and more. The pick
method allows you to extract specific properties from an object while ignoring others.
In this benchmark, Lodash's pick
method is used to filter the object
structure and extract only certain properties (e.g., type
, subtype
, etc.).
Special JS Features or Syntax
The test cases use a special JavaScript feature: Closure. In the code snippet, map()
function returns an array of new functions that are created when each iteration of the loop completes.
These functions capture the current value of element
in their scope and then call the pick()
method on it. This is possible due to JavaScript's closure behavior, which allows variables from outer scopes (like i
) to be accessible within inner functions (the new function created for each iteration).
Other Alternatives
In addition to Lodash's pick
method and native JavaScript's pick
function, there might be other libraries or implementations that offer similar functionality. Some alternatives could include:
underscore.js
, moment.js
, or fast-json-pick
Chrome's chrome.experimental.pick()
)However, it's worth noting that Lodash's pick
method is one of the most well-known and widely used alternatives, so it's likely to be the primary focus in such benchmarks.