<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/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 _.omit(
element,
'card_last4',
'card_type',
);
});
arr.map(function (element) {
const {
card_last4,
card_type,
rest
} = element;
return rest;
});
arr.map(function (element) {
return {
type: element.type,
subtype: element.subtype,
card_exp_month: element.card_exp_month,
card_exp_year: element.card_exp_year,
card_country: element.card_country,
something: element.something
};
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash | |
Native | |
Manual omit |
Test name | Executions per second |
---|---|
Lodash | 4.6 Ops/sec |
Native | 10.2 Ops/sec |
Manual omit | 127.3 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
Benchmark Definition
The benchmark is designed to compare three approaches:
omit
, for working with objects.Options Compared
We're comparing the performance of each approach on a large dataset of 100,000 objects. The benchmark measures the time it takes to execute each approach using the map
function on this dataset.
Pros and Cons of Each Approach
Library - Lodash
Lodash is a popular JavaScript utility library that provides various functions, including omit
, for working with objects. The omit
function takes two arguments: the object to be modified and an object containing properties to remove from the original object. In this benchmark, we're using the lodash.min.js
file from a CDN.
Special JS Feature/Syntax - Native Destructuring
Native destructuring is a syntax feature introduced in ECMAScript 2018 (ES10) that allows us to extract specific properties from an object while ignoring others. The syntax is similar to array destructuring, but applied to objects. In this benchmark, we're using native destructuring with the const
declaration and rest parameter (...rest
) to achieve a similar effect to Lodash's omit
function.
Benchmark Preparation Code
The script preparation code creates an empty array arr
and an object object
with various properties, including some that we want to omit in the benchmark. The code then pushes this object 100,000 times into the arr
array using a loop.
Html Preparation Code
The HTML preparation code includes a script tag pointing to Lodash's CDN file, which is used by the benchmark.
Other Alternatives
If you're interested in exploring alternative approaches or testing other libraries, here are some options:
...rest
) and destructuring assignment ({ ...rest }
).omit
.omit
, such as Ramda, Moment.js, or React.Keep in mind that each approach has its pros and cons, and the choice of which one to use depends on your specific requirements and performance constraints.