Search code examples
javascriptcompilationprototype

javascript extending prebuilt prototypes performance


Many people argue that extending the prebuilt prototypes such as for String, Array or Object is bad practice.

However, others say that it also has terrible performance hits - which makes sense since I presume caching methods in some sort hash table is now invalidated (since you could have changed that method).

What I want to know is that if you all of your prototype extending of native types once at the beginning of execution, and before any objects containing this prototype in their prototype chain are used, will this still have performance problems?

The reason I ask is because I'm working on a system which compiles to javascript. I don't care about what is bad practice in javascript, but I definitely care about performance!


Solution

  • Like @Jonas say's, performance is most likely not going to be an issue.

    Extending the prototype is in fact how a lot of pollyfills work.

    But the question you have to ask, do you plan on using any third party libs, or are you planning on making this into a library for others to use. If so, avoid the overriding built in prototype's as it could break a lots of things..

    If this is only ever going to be used internally, with your control I can't see there be any problems, as long as you don't do something silly to the built in's of course.

    For extra safety, I would also think about prefixing all your methods with something unlikely to become part of the specifications.. eg.. String.prototype.myCaptializer, I very much doubt this will ever become part of the spec..