isoneof-vs-indexof

JavaScript performance comparison

Revision 2 of this test case created by Tom MacWright

Info

A simple hack that I constantly use to get little performance boosts.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    function isoneof(x) {
        var options = {};
        for (var i = 0; i < x.length; i++) options[x[i]] = true;
        return function(y) {
            return options[y] === true;
        };
    }
   
    var options = [];
    for (var i = 13; i < 100; i++) {
    options.push(String.fromCharCode(i));
    }
   
    var choices = ['a', 'k', 'z'];
    function getchoice() {
    var choices = ['a', 'k', 'z'];
    var i = Math.round(Math.random() * 3);
    return choices[i];
    }
    var decider = isoneof(options);
};
</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
indexOf
var i = 0;

if (choices.indexOf(getchoice()) !== -1) i++;
pending…
isoneof
var i = 0;

if (decider(getchoice())) i++;
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