JavaScript Inheritance Performance

Written by on February 18th, 2009 in Uncategorized.

Robert Kieffer has run some benchmarks on the performance of JavaScript inheritance using different inheritance techniques:

One area of the Prototype JavaScript library that I have a bit of a love-hate relationship with is its support for mimicing OO inheritance.   The ability to call $super from within a function to refer to a superclass’ implementation is pretty darn cool, but I’ve I’ve found myself more and more annoyed at having to navigate what seem like unnecessarily deep and complicated stack traces when trying to debug code.  It was while mired in the bowels of Class.create() and Class#addMethods() that I found myself wondering how much of a performance penalty this stuff was incurring.  To find out, I put together a test to determine how different the strategies for emulating OO inheritance in JavaScript performed.  Here’s what I tested:

  • Ad hoc inheritance - This is a common(?) homebrew technique for allowing prototypes to leverage the code in objects further up the prototype-food chain.  Methods are overridden by keeping a reference to the parent method in a separate property , which can then be invoked as needed.  It’s fast but not very pretty, and it’s arguable whether or not this qualifies as real “OO” inheritance.
  • Prototype-style inheritance - Prototype uses a strategy inspired by Alex Arenell’s Inheritance library. Subclass methods declare a “$super” argument that is set up by Prototype to reference the superclass’ method.
  • Base2-style inheritance - Dean Edwards’ library.  Subclass methods invoke “this.base()” to call their superclass’ implementation.
  • John Resig inheritance - JR, of jquery fame, experimented with a Base2 variant which he published on his blog.  It’s a bit simpler than Base2, but seemed worth testing.

Tests were performed by using  JSLitmus to create a Inheritance Performance testbed.

Robert shows that when $super is used, you get a perf drop with Prototype, however he also realizes that this is “only really important if you’re making 100,000’s of calls per second to overridden methods, however.”

Source: Ajaxian » Front Page
Original Article: http://feeds.feedburner.com/~r/ajaxian/~3/542404753/javascript-inheritance-performance

Comments are closed.



Site Navigation