Reputation: 13686
I was looking at some code (https://github.com/einaros/tinycolor/blob/master/tinycolor.js) that adds to the prototype of the String
object in javascript.
I was wondering how to assume the overhead of adding to the String
prototype, as it applies to any string handling (cpu, memory) that doesn't require these additions. That's because I probably wouldn't find it useful to get overhead for all string manipulations just for this small shim, and I guess it's also a good time to get more friendly with javascript prototype manipulation of the native types.
As the topic has been endlessly discussed in various contexts, any pointer to an existing good or simple analysis would be helpful, or a succinct-yet-correct explanation. It's a bit hard to land using a Google keyword search..
Thanks!
Upvotes: 1
Views: 361
Reputation: 224877
That's because I probably wouldn't find it useful to get overhead for all string manipulations just for this small shim
If there’s a performance cost, this is definitely not it. When you create a string, it’s not as if it copies all of the prototype methods over; any properties are looked up from the prototype chain as required (i.e. when you call the method).
People avoid adding methods to other prototypes for a different reason – it mixes code together and can create conflicts. (See Prototype.js, a library that revolves [or revolved] entirely around extending builtins.) Instead, you can use a function – oft underappreciated with all this OOP nonsense going around lately. ;)
Upvotes: 3