Last active
August 22, 2023 10:51
-
-
Save dejurin/30fd43b92fcf5bd0ce7c59baff2beb9a to your computer and use it in GitHub Desktop.
Object is Empty: benchmark ways
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Benchmark = require('benchmark'); | |
const isEmpty = require('lodash/isEmpty'); | |
const suite = new Benchmark.Suite(); | |
console.log('benchmark'); | |
const emptyObj = {}; | |
const nonEmptyObj = { key: 'value' }; | |
suite | |
.add('Object.keys', function() { | |
Object.keys(emptyObj).length === 0; | |
}) | |
.add('for...in Loop', function() { | |
for (const key in emptyObj) { | |
if (emptyObj.hasOwnProperty(key)) { | |
return false; | |
} | |
} | |
return true; | |
}) | |
.add('Object.getOwnPropertyNames', function() { | |
Object.getOwnPropertyNames(emptyObj).length === 0; | |
}) | |
.add('JSON.stringify', function() { | |
JSON.stringify(emptyObj) === '{}'; | |
}) | |
.add('isEmpty', function() { | |
isEmpty(emptyObj); | |
}) | |
// Add more methods to benchmark here | |
.on('cycle', function(event) { | |
console.log(String(event.target)); | |
}) | |
.run({ async: true }); | |
/* | |
Chip: Apple M1 Max | |
Memopry: 32 GB | |
*/ | |
/* | |
Object.keys x 177,339,177 ops/sec ±0.65% (94 runs sampled) | |
for...in Loop x 111,380,046 ops/sec ±0.36% (100 runs sampled) | |
Object.getOwnPropertyNames x 171,856,296 ops/sec ±1.08% (97 runs sampled) | |
JSON.stringify x 19,808,391 ops/sec ±0.36% (97 runs sampled) | |
isEmpty x 74,750,856 ops/sec ±0.21% (99 runs sampled) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment