chair ring

JavaScript performance comparison

Revision 3 of this test case created

Info

go around a ring of 100 removing every second chair (starting at the first chair)

This is a look to see how an array based solution would do against a custom data structure.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    if (!Array.prototype.filter)
    {
      Array.prototype.filter = function(fun /*, thisp */)
      {
        "use strict";
     
        if (this == null)
          throw new TypeError();
     
        var t = Object(this);
        var len = t.length >>> 0;
        if (typeof fun != "function")
          throw new TypeError();
     
        var res = [];
        var thisp = arguments[1];
        for (var i = 0; i < len; i++)
        {
          if (i in t)
          {
            var val = t[i]; // in case fun mutates this
            if (fun.call(thisp, val, i, t))
              res.push(val);
          }
        }
     
        return res;
      };
    }
};
</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
array
        
        // setup array
        var chairArr = [];
        for (var i = 1; i <= 100; i++)
                chairArr.push(i);

        // whether to remove odd or even chairs
        var odd = 0;

        // while there are still chairs
        while (chairArr.length > 1) {

                // remember the initial length
                var last = chairArr.length;

                // filter odd or even chairs
                chairArr = chairArr.filter(function (val, ind) {
                        return (ind + odd) % 2
                });

                // used to decide odd or even chairs next round
                odd += last;
        }

        // return the answer
        chairArr[0];

 
pending…
custom data structure
// setup chair ring
var start = {num:1};
var one = start;
for(var i = 2; i <= 100; i++) {
        var temp = {num:i};
        start.next = temp;
        start = temp;  
}
start.next = one;
one = null;

// go around removing chairs
while(start.next != start) {
        start.next = start.next.next;
        start = start.next;
}
start.num;
pending…
array sol'n 2
        
        // setup array
        var chairArr = [];
        for (var i = 1; i <= 100; i++)
                chairArr.push(i);

        for (i = 1; i < chairArr.length; i+=2)
    chairArr.push(chairArr[i]);

       

        // return the answer
        chairArr.pop();
 
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment