views:

84

answers:

1

I realize that adding methods to native JavaScript objects (Object, Function, Array, String, etc) is considered bad practice by some, but is there also a performance hit associated with this?

Would instances of native objects take longer to create and/or use up more memory if their prototype has been extended with additional methods?

+6  A: 

Would instances of native objects take longer to create and/or use up more memory if their prototype has been extended with additional methods?

No. Neither of those things should happen: each object must maintain a reference to its prototype, but that reference won't get any larger or take any longer to retrieve if more properties are added to the object it references.

Now, if you were to add enough additional methods to the prototype, it might start to impact the time needed to look up methods on the objects of that type. This will vary by implementation, but i would be shocked if you ever noticed a difference (i suspect you'd drive yourself mad trying to remember the names of all those additional methods long before it had a noticeable impact on runtime speed).


Edit: here's a quick & ugly test - it creates 500K instances of Array before and after adding 500K custom methods to the Array.prototype object. No appreciable difference; no worries...

Shog9
Extending the javascript method lookup chain through multiple prototypes increases lookup time since prototype traversal is O(n), but method lookup on a single prototype is constant-time O(1).
Duncan Beevers