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

时光总嘲笑我的痴心妄想 提交于 2019-12-12 08:01:22

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/14294030/impacts-and-benefits-of-creating-empty-object-using-object-createnull

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!