<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
console.log(!_.isEmpty(undefined))
console.log(!!Object.keys(Object(undefined)).length)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash isEmpty | |
Object.keys().length |
Test name | Executions per second |
---|---|
Lodash isEmpty | 538080.9 Ops/sec |
Object.keys().length | 518148.2 Ops/sec |
The benchmark defined in the given JSON tests the performance of two different approaches to checking if an object (specifically undefined
in this case) is empty. The two approaches utilized in this benchmark are:
_.isEmpty()
methodObject.keys().length
Lodash _.isEmpty()
isEmpty
method checks if a value is an object or an array and returns true
if it has no own enumerable properties._.isEmpty(undefined)
will return true
since undefined
is not an object and does not have any properties.Object.keys().length
Object.keys()
retrieves an array of a given object's property names. Then, by checking the length of that array, you can determine if the object has properties or not.Object.keys(Object(undefined)).length
returns 0
because Object(undefined)
produces an empty object, and thus it has no own properties, resulting in a length of 0
. The double negation (!!
) converts this length to a boolean.Lodash _.isEmpty()
Object.keys().length
undefined
, which is a unique case since neither method is typical for testing emptiness directly against undefined
. _.isEmpty
performs slightly better in terms of executions per second compared to the Object.keys().length
method in this specific case.In addition to the two tested methods, some other options to check for emptiness include:
value === null || value === undefined
: This is a very basic check that can be effective if you are simply checking for null
or undefined
.for..in
loop: You could iterate over an object's properties to ascertain if it has any. However, this approach can become cumbersome and less efficient compared to using built-in methods.Overall, the choice between these methods can depend on the specific use case, code readability preference, and performance needs.