Impacts and benefits of creating empty object using Object.create(null)
Asked Answered
C

1

8

First of all, I made a quick jsperf test case to show the obvious :
Object.create(null) is way slower than creating a object with the {} syntax.
http://jsperf.com/js-object-creation-null-proto

But given this fact, can the former case be a good alternative sometimes concerning optimization and performance? In other words, does manipulating the most lightweight js object can increase performance enough so that it became a reasonable choice to use it in some cases.

I am refering to cases where you are going to access the object properties a lot, or making an heavy use of the for in loop for example.

Is this method too much risky to be used in a library where people could be lead to heandle these object that doesn't own the standard properties bring by the standard Object prototype?

Also, do you know another (quicker) way to create the most lightweight js object?

PS : I made a brief test case to show a case where using a Object.create(null) and accessing properties is a little more quickier than with {}.
http://jsperf.com/js-object-creation-and-accessing-properties

Catricecatrina answered 12/1, 2013 at 14:0 Comment(0)
B
8

I think creating objects with Object.create(null) generally unnecessary and not worth the browser compatibility and clarity you sacrifice. When you create an object with the {} syntax you are essentially doing Object.create(Object.prototype), which creates an object with access to the properties in Object.prototype. This means that you have access to methods like toString and hasOwnProperty directly from the object, but can also override them if you want — although you should avoid this if possible. As for performance, the difference is very small with only two properties on the object (as demonstrated on jsperf). If your object had hundreds or thousands of properties the difference would be almost nonexistent.

In conclusion, if you wan't your code to perform better you should always strive for clarity and try to improve the high level, algorithmic design of your code (not that you haven't already); and only worry about micro-optimizations only when absolutely necessary.

Behah answered 18/1, 2014 at 20:4 Comment(2)
I agree with your conclusion about favoring quality over micro-optimizations, it's an important point that I sometimes forget.Catricecatrina
Highlight : improve the high level, algorithmic design of your code; and only worry about micro-optimizations only when absolutely necessary.Pagan

© 2022 - 2024 — McMap. All rights reserved.