Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top