String In Array

JavaScript performance comparison

Test case created by Dom

Info

Tests for fastest way to determine if a string is in an array

Preparation code

<script>
function asObject(a)
{
    var o = {};
    for (var i = 0; i < a.length; i++)
    {
        o[a[i]] = '';
    }

    return o;
}
</script>
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script>
Benchmark.prototype.setup = function() {
    var testArray = ['a', 'b', 'c', 'd', 'e'];
    var testObject = { 'a': '', 'b': '', 'c': '', 'd': '', 'e': ''};
    var testFor = 'f';
};
</script>

Preparation code output

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Switch
switch (testFor)
{
    case 'a':
    case 'b':
    case 'c':
    case 'd':
    case 'e':
    case 'f':
        return true;
    default:
        return false;
}
pending…
In Array (foreach style)
for (var i in testArray) {
    if (testArray[i] == testFor) {
        return false;
    }
}

return true;
pending…
In Map
return (testFor in testObject);
pending…
Convert Array to Object
return (testFor in asObject(testArray));
pending…
Array (for loop style)
for (var i =0; i < testArray.length; i++) {
    if (testArray[i] == testFor) {
        return false;
    }
}

return true;
pending…
Key exists (undefined)
return typeof(testObject[testFor]) !== 'undefined'
pending…
Key Exists
return testObject[testFor] != null
pending…
Underscore Index Of
return (_.indexOf(testArray, testFor) != -1)
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