I'm currently writing a library of extension methods to many different Javascript objects. Is there any performance considerations if, for example, i add over 200 methods to different objects (through their prototypes) in the same s开发者_运维百科ource file?
EDIT: Just for information, i'm extending the built-in objects.
No, there will be almost no performance hit. Even attaching the functions to the prototype(s) should only take a few ms (maybe 5ms) and beyond that you have 200 functions sitting in memory in one spot, never being copied, you will never notice anything. Assuming, of course, that you are attaching to .prototype of something.
As for why there is no speed hit: In order to resolve a function call on an object: foo.doSomething()
, the internal engine needs to walk the object scope and prototype chain of that object. Basically, it does this:
if(Object.hasOwnProperty('doSomething')){ // run Object.doSomething
if(Object.__proto__.hasOwnProperty('doSomething')){ // run Object.__proto__.doSomething
while(Object.__proto__.__proto__.__proto__.....){ // repeat
Every layer of this is a hash, so lookups are constant time. In terms of lookup speed, it doesn't matter if there's 2 or 2 million functions in a prototype chain (Although if you have 2 million you'll be eating tons of memory).
For reference: jQuery has 511 functions internally. 200 isn't that many at all
Side note: DO NOT EXTEND Object.prototype
-- JUST DON'T. You break for-in loops if you do this, or at least come very close to breaking them if people don't use explicit if(obj.hasOwnProperty(foo))
checks. You'll also make for-in loops slower on object hashes which is the ONLY potential slow-down you'll ever encounter extending prototypes.
And PLEASE don't extend Array.prototype
-- it annoys me. But plenty of other people do it, so it's not -as- bad... The argument is that you're not supposed to use for-in loops on Arrays, and many people now don't because of Prototype.js, but you should still be allowed to if you want to!
精彩评论