<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
cspSrcs = {
key: 'value'
};
for (let i = 0; i < 1000; ++i) {
cspSrcs['a' + i] = i;
}
_.isEmpty(cspSrcs);
Object.keys(cspSrcs).length === 0 && cspSrcs.constructor === Object;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
_.isEmpty | |
Native JavaScript |
Test name | Executions per second |
---|---|
_.isEmpty | 15399.8 Ops/sec |
Native JavaScript | 16091.3 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared, and the pros/cons of each approach.
Benchmark Definition
The benchmark compares the performance of two approaches:
isEmpty
functionThe Lodash isEmpty
function checks if a value is an empty object, collection, map, or set. The native JavaScript code checks if an object has no own enumerable string keyed properties.
Script Preparation Code
This code creates an object cspSrcs
with 1000 keys and assigns each key a unique integer value. This object will be used to test the performance of the two approaches.
Html Preparation Code
The HTML code includes a reference to the Lodash library, which is used by the benchmark. The integrity attribute ensures that the loaded script is not tampered with.
Individual Test Cases
There are two test cases:
_.isEmpty(cspSrcs);
: This test case uses the Lodash isEmpty
function to check if the cspSrcs
object is empty.Object.keys(cspSrcs).length === 0 && cspSrcs.constructor === Object;
: This test case uses native JavaScript code to check if the cspSrcs
object has no own enumerable string keyed properties.Pros and Cons of each approach
isEmpty
function:Other considerations
The benchmark also includes metadata about the test run, such as the browser type, device platform, operating system, and execution frequency per second. This information can be useful for understanding the performance characteristics of different browsers and devices.
Alternative approaches
Some alternative approaches to checking if an object is empty in JavaScript include:
for...in
loop to check if all enumerable properties have a value: for (var prop in obj) { if (obj.hasOwnProperty(prop)) return false; }
Object.keys()
and checking the length of the resulting array: if (Object.keys(obj).length === 0) { ... }
However, these approaches may not be as fast or convenient as the Lodash isEmpty
function or native JavaScript code.