JavaScript optimization versus inlining

JavaScript performance comparison

Test case created

Info

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

 
<script>
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;
};
</script>

Test runner

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

Java applet disabled.

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

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

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

assertEquals( 10000, numWords );
pending…

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

Compare results of other browsers

0 comments

Add a comment