JavaScript optimization versus inlining

JavaScript performance comparison

Test case created


This test will check whether JavaScript engines such as V8 are clever enough to inline functions and get rid of overhead.

Please note that in any case, readability and maintainability of code are more important than fractions of milliseconds and that inlining is a form of code duplication that should be avoided.

Preparation code

Benchmark.prototype.setup = function() {
    /* Test 1: Prototype */
    String.prototype.countWords = function() {
      return this.match( /\S+/g ).length;
    /* Test 2: Global function */
    function countWords (str) {
      return str.match( /\S+/g ).length;
    function assertEquals(expected, found) {
      if( expected !== found ) {
        console.log( 'Assertion Error: Expected <' + expected + '> but found <' + found + '>.' );
    var testText = Array(10001).join('word ');
    var numWords;

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
numWords = testText.countWords();

assertEquals( 10000, numWords );
Global function
numWords = countWords( testText );

assertEquals( 10000, numWords );
numWords = testText.match( /\S+/g ).length;

assertEquals( 10000, numWords );

You can edit these tests or add even more tests to this page by appending /edit to the URL.

Compare results of other browsers


Comment form temporarily disabled.

Add a comment