Why is Object.create so much slower than a constructor?

后端 未结 4 1599
南旧
南旧 2021-02-07 12:00

Background

In a project I\'m maintaining we make extensive use of null prototype objects as a poor man\'s alternative to (string key only) Maps, which are not natively

4条回答
  •  灰色年华
    2021-02-07 12:16

    The performance difference has to do with the fact that constructor functions are highly optimized in most JS engines. There's really no practical reason that Object.create couldn't be as fast as constructor functions, it's just an implementation-dependent thing that will likely improve as time goes on.

    That being said, all the performance test proves is that you shouldn't be choosing one or the other based on performance because the cost of creating an object is ridiculously low. How many of these maps are you creating? Even the slowest implementation of Object.create on the tests is still chugging out over 8,000,000 objects per second, so unless you have a compelling reasons to create millions of maps, I'd just choose the most obvious solution.

    Furthermore, consider the fact that one browser implementation can literally be 100s of times faster than another implementation. This difference is going to exists regardless of which you pick, so the small difference between Object.create and constructors shouldn't really be considered a relevant difference within broader context of different implementations.

    Ultimately, Object.create(null) is the obvious solution. If the performance of creating objects becomes a bottleneck, then maybe consider using constructors, but even then I would look elsewhere before I resorted to using something like Empty constructors.

提交回复
热议问题