Fastest empty object check in JavaScript
A benchmark I thought could help others
January 20, 2025
Recently, at work, I was required to check for an object being empty or not with potentially important consequences for performance given the object being checked for could be arbitarily large.
Going by Romain's excellent internal guide ( here's a more general, public version ), I was hesitant about using Object.keys(obj).length === 0
, so decided to test the options out for myself.
const isObjEmpty1 = (obj) => {
for (const k in obj) {
if (Object.hasOwn(obj, k)) return false
}
return true
}
const isObjEmpty2 = (obj) => Object.keys(obj).length === 0
const isObjEmpty3 = (obj) => Object.getOwnPropertyNames(obj).length === 0
Testing performance of different methods to check if an object is empty. Lower time and relative speed (1.00x) indicate better performance.
Test conditions: Normally distributed object sizes (0-1000 keys), 5000 iterations
Result
I found that Object.keys(obj).length === 0
seems to reliably be fast, with a for ... in
-based, iterative method only negligibly slower. Feel free to use this to check for empty objects, fast.