1

I can create object using prototype, and the fields are set in the constructor, or I can create object using JSON. I'd expect that the prototyped version will be as fast as the literal, or faster, but it occurs that it's slower on chrome and ff, while on Opera both seem to be equal.

http://jsperf.com/object-literal-vs-object-prototype-field-access-time

Can someone explain it?

1 Answer 1

3

AFAIK prototype access is basically just 2 normal accesses (except that access to the prototype is highly optimized). Writing this.test is basically the same as writing

if(this.hasOwnProperty('test')) { return test; }
else { return this.constructor.prototype['test']; }

Though, I'm not 100% sure of this.

Sign up to request clarification or add additional context in comments.

2 Comments

So I should understand, that when using non-prototyped object, hasOwnProperty function is not called at all?
Well, internally it's probably technically never called, and there's probably several layers of caching (that I have no idea how work) to speed up everything. Also, I think (which I forgot when I made the answer) that when you access a prototype-value the value is copied to the object in question, though I'm not sure about that... However, if you ignore the caches (that might or might not be there), you always have to check hasOwnProperty, cause how else would you know what to return? What's important to remember is that the prototype-lookup works the same way (new hasOwnProperty).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.