FunctionSource, Your Source for Developer News

A Prototypal Discussion

Posted by Dion Almaer about a year ago on javascript language performance

Christopher Chedeau has added a piece on how prototypal inheritance works that details the differences between new and why we now also have Object.create.

It spurred some good discussion there people talked about whether you can use some of this today.

Jeremy Ashkenas (CoffeeScript++) said:

I’m sorry to be difficult about this, but … Like many other Crockford-inspired takes on the subject, vjeux’s article is massively bad advice.

Firstly, __proto__ is nonstandard, and deprecated. If you write JavaScript that uses it, it won’t run in all JS runtimes.

Object.create is similarly not available everywhere. It’s not available in Firefox < 4, IE < 9, or any version of Opera. Crockford's version of Object.create is not compatible with the native Object.create — and if you patch it in, you may end up breaking libraries that expect the real thing.

But let's say you had it all sorted out, and you had a sane plan for using the native Object.create, and falling back to Crockford's implementation where unavailable … it's still not a great pattern.

Running that again today, I see that in Chrome, instantiating objects via Object.create — either Crockford’s or native — is over 95% slower than using a regular constructor function. We’re talking about just creating basic objects here, low-level stuff: how fast you can do it is pretty important if you’re aiming for high-performance JavaScript.

The prototype property, constructor functions, and “new” are the way that JavaScript objects work, and the way that engines are tuned to optimize JS code. Avoid learning to use them at your own peril.

Now, I don’t think that Christopher was writing the post in a “use this now!” vein, but rather in a “let’s discuss prototypal inheritance and how it works” one, but is is good to talk about the real world issues today too.

I don’t know if I would worry too much about the micro-benchmark unless it is an issue in your application. For one, it was pointed out that the poor performance in Object.create was a large reason that V8 did relatively poorly, but if we know anything about the js performance wars…. they catch up quickly. Also, I remember doing some JavaScript tuning on Bespin, and then once we ran Shark on the application we quickly saw that JS wasn’t the issue at all. As always, measure first.

It does give us a reminder yet again that having classes in the language, in a js way will be nice to have indeed.