1

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!

matanster
  • 15,072
  • 19
  • 88
  • 167
  • 1
    First you must understand how [prototype](http://stackoverflow.com/questions/572897/how-does-javascript-prototype-work) works. Since there only is one prototype shared by all strings, it only uses memory for once instance of your function. If your code isn't private you should probably avoid to add things to built in objects. – some Dec 24 '13 at 16:13

1 Answers1

3

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. ;)

Ry-
  • 218,210
  • 55
  • 464
  • 476
  • Sure, and thanks :) Yet I guess adding functions to the (String) prototype may slow down calling functions on strings, or other string handling whenever the javascript interpreter looks up functions on the String prototype if ever. I could figure the actual impact with some heavy experimentation, if I really wanted to, or delve into open-sourced browser source code for it. Do you think modern browsers just use a data structure, for prototype functions, that has a constant lookup time regardless the amount of functions included or referenced by it? – matanster Dec 27 '13 at 17:24
  • @matt: You don’t have to worry about that part at all – the place where performance is affected in any significant way (well, *usually*! Everything here is *usually* `=)`) would be when you’re calling that particular function added to the prototype. Anything else should stay the same. – Ry- Dec 27 '13 at 20:43