Which is faster: obj.hasOwnProperty(prop) vs Object.keys(obj).includes(prop)

twitter logo ・1 min read

I don't know how to test runtime speed but I'm interested in which of these methods would cause more overhead.

Given an object with n properties (also called keys) is it faster to check if that property exists using obj.hasOwnProperty(prop) or Object.keys(obj).includes(prop). Something to consider is what if you need to check multiple properties multiple times?

If you store the keys in a variable: const keys = Object.keys(obj) and then make a series of checks keys.includes(prop1); keys.includes(prop2); is this faster or slower than obj.hasOwnProperty(prop1); obj.hasOwnProperty(prop2);

twitter logo DISCUSS (6)
markdown guide
 

I bet it has to be Object.hasOwnProperty.

Depending on the runtime implementation, Object in JavaScript should be somewhat similar to a HashMap. So a key lookup should be O(1). Array.includes on the other hand is obviously O(n). They really are not very comparable.

Object.hasOwnProperty would be more comparable to the in operator. in should be a little bit more complicated as it looks through the prototype chain as well. But for keys that are already attached to an Object, I suppose it should give a similar, if not the same, time complexity.

 
 

I like testing execution time with console.time(string) and console.timeEnd(string).

Though, as one could guess testing performance this way is a fail. It will give various results every time. You'd better use developer tools instead.

Anyway, Object.hasOwnProperty compared to prop in obj should be incredibly faster as the latter run through all the prototype chain of an object. I've run that tests on small objects and get what I expected.

 
Classic DEV Post from Sep 25 '18

How do you shift between the coding mindset and other head spaces?

Ethan Arrowood profile image
Future Microsoft Core Services Engineer Intern Summer 2018. Computer Science student at Wentworth Institute of Technology.

Sore eyes?

dev.to now has dark mode.

Go to the "misc" section of your settings and select night theme ❤️