1

I need the most efficient way to enumerate the own properties of an object in Javascript. I'm of course aware of the for...in pattern, but according to my tests, it is really a performance gotcha in some scenarios and I would like to work it around somehow.

To be clear, I mean the following basic snippet.

for (var key in myObject) { if (!myObject.hasOwnProperty(key)) continue; ... } 

I've been thinking about some kind of caching but that's not trivial and also would not allow to catch the properties real-time.

Any suggestions or hints are appreciated.

UPDATE

Turned out based on my small performance test that in a modern browser Object.keys can have huge advantage over other techniques.

http://jsperf.com/enumerating-object-properties

1 Answer 1

2

did you tried getOwnPropertyNames() ? or even Object.keys()?

can you also share the results of performance testing you have done?

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, I can learn something new here every day. I wasn't aware of these methods. Actually I've put together a test and it came out that Object.keys is significantly faster than the others (at least in Chrome 46). Here is the test: jsperf.com/enumerating-object-properties
Now in end of 2016 interestingly enough it seems like the for...in loop is significantly faster than the others in latest Chrome.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.