<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
const data = {}
console.log(!_.isEmpty(data))
const data = {}
console.log(!Object.keys(data).length)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash isEmpty | |
Object.keys().length |
Test name | Executions per second |
---|---|
Lodash isEmpty | 526673.9 Ops/sec |
Object.keys().length | 536897.4 Ops/sec |
The benchmark provided compares two methods for checking if an object is empty in JavaScript: using Lodash's _.isEmpty()
and using the native Object.keys().length
method. Here’s a detailed breakdown of what’s tested:
Lodash _.isEmpty(data)
_.isEmpty()
function checks if the provided value is an object that has no enumerable properties.Native JavaScript Object.keys(data).length
Object.keys()
method to retrieve an array of the object's own property names and then checks the length of that array. If the length is 0, it indicates that the object is empty.Lodash _.isEmpty(data)
Pros:
Cons:
Native JavaScript Object.keys(data).length
Pros:
Cons:
The benchmark shows the execution speed of both methods in terms of ‘Executions Per Second’. In this case, Object.keys().length
scored 536,897.375, while _.isEmpty()
scored 526,673.875. This indicates that the native method can execute slightly faster than the Lodash method in the tested environment.
Given that this benchmark was executed in a controlled environment (Chrome 131 on Mac OS X), results can vary significantly on different browsers or operating systems.
Other ways to check if an object is empty include:
Using the for...in
loop: This method involves iterating over the object's properties directly and returning false if any properties are found. Example:
function isObjectEmpty(obj) {
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
return false;
}
}
return true;
}
JSON.stringify: A less efficient, but interesting approach is checking the serialized version of the object:
const isEmpty = (obj) => JSON.stringify(obj) === '{}';
However, this can have significant performance costs and may also be less clear semantically.
In summary, this benchmark explores two methodologies for checking if an object is empty, weighing readability and performance against each other, especially for use cases that may involve either Lodash or purely vanilla JavaScript. Each method has scenarios where it might be preferred based on project needs, team familiarity with libraries, and performance considerations.