<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var foo = {bar: 1};
_.has(foo, 'bar');
foo.hasOwnProperty('bar');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash has | |
hasOwnPropertie |
Test name | Executions per second |
---|---|
lodash has | 7442246.0 Ops/sec |
hasOwnPropertie | 778454528.0 Ops/sec |
Let's break down the provided benchmark JSON and explain what's being tested.
Benchmark Definition
The benchmark is defined by two test cases:
_.has(foo, 'bar');
: This test case uses the Lodash library to call the has
function on an object foo
, checking if a property named 'bar'
exists.foo.hasOwnProperty('bar');
: This test case manually checks if the foo
object has a property named 'bar'
using the hasOwnProperty
method.Options Compared
The two test cases compare the performance of:
has
function (_.has(foo, 'bar')
) versushasOwnProperty
(foo.hasOwnProperty('bar')
)Pros and Cons
Using Lodash's has
function has several advantages:
Pros:
has
function can be used to check for multiple properties, making it a more flexible option.Cons:
On the other hand, manual checking with hasOwnProperty
has some advantages:
Pros:
Cons:
hasOwnProperty
can lead to more verbose code when checking for multiple properties.Library - Lodash
Lodash is a popular JavaScript utility library that provides a wide range of functions for tasks such as:
has
, isEmpty
, pick
)compact
, curry
)In this benchmark, Lodash's has
function is used to check if an object has a specific property. The _.has(foo, 'bar')
test case demonstrates the use of this function.
Special JS feature - ES6 Optional Chaining
The benchmark uses ES6 optional chaining (?.
) in its HTML preparation code:
<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
Optional chaining allows you to access nested properties of an object without throwing an error if the property is null or undefined.
Other Alternatives
If you don't want to use Lodash's has
function, you can implement your own version using the following approach:
function has(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
This implementation uses the hasOwnProperty
method from the Object
prototype to check if an object has a specific property.
Alternatively, you can use other JavaScript libraries or frameworks that provide similar functionality, such as:
has
function.in
operator and the hasOwnProperty
method are available in modern browsers without any external dependencies.Keep in mind that these alternatives may have different performance characteristics and usage patterns compared to Lodash's has
function.