<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.4/lodash.min.js"></script>
var person = {name: 'Frederick', lastName: 'Corcino Alejo'};
_.has(person, 'name');
person.hasOwnProperty('name')
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash has | |
JavaScript Native hasOwnProperty |
Test name | Executions per second |
---|---|
Lodash has | 18728764.0 Ops/sec |
JavaScript Native hasOwnProperty | 57678144.0 Ops/sec |
I'll break down the benchmark and explain what's being tested, compared options, pros and cons of those approaches, library usage, special JavaScript features or syntax, and alternatives.
Benchmark Overview
The MeasureThat.net benchmark compares the performance of two approaches to check if a property exists in an object: JavaScript native hasOwnProperty
and Lodash's _has
.
Test Cases
There are two individual test cases:
_has
method._.has(person, 'name');
hasOwnProperty
method.person.hasOwnProperty('name')
Library Usage
Lodash is a popular utility library for JavaScript that provides various functions to perform common tasks, such as array manipulation, string manipulation, and object manipulation (including checking if properties exist). In this benchmark, Lodash's _has
function is used to check if a property exists in an object.
Special JavaScript Features or Syntax
None mentioned in the provided code. However, it's worth noting that some versions of JavaScript have specific syntax for iterating over object properties using for...in
or Object.keys()
. This benchmark doesn't use these features explicitly.
Approach Comparison
The two approaches being compared are:
_has
method: Lodash provides a simple and efficient way to check if a property exists in an object. The _has
function takes two arguments: the object to search, and the property name.hasOwnProperty
method: This is a built-in method of JavaScript objects that checks if a given property belongs to the object.Pros and Cons
Here are some pros and cons of each approach:
Lodash's _has
method:
Pros:
Cons:
JavaScript Native hasOwnProperty
method:
Pros:
Cons:
_has
Other Considerations
When choosing between these two approaches, consider the following factors:
hasOwnProperty
is a built-in method, it may be slightly faster due to its lower overhead._has
method is generally more readable and easier to understand, especially for those unfamiliar with the native method.Alternatives
Other approaches to check if a property exists in an object include:
in
operator (e.g., person['name'] in person
)Object.prototype.hasOwnProperty.call(person, 'name')
Array.prototype.includes()
or Set.prototype.has()
, depending on the context (arrays or sets)These alternatives may have different performance characteristics and trade-offs compared to Lodash's _has
method and JavaScript native hasOwnProperty
method.