Array indexOf vs. Object key lookup

Benchmark created by Thomas Kindl on


Description

Test for presence of an entry in an object/dictionary vs array search using indexOf. In addition the impact of the dictionary size is compared. For array search, the entry in the middle of the array is looked up.

Setup

// generator for keys, object/dictionary and array
    
    function generateRandomKey(keyLength) {
        var key = "";
        for (var i = 0; i < keyLength; i++) {
                key += String.fromCharCode("a".charCodeAt(0) + Math.floor(26 * Math.random()));
        }
        return key;
    }
    
    function generateDict(numEntries, keyLength) {
        var dict = {};
        var key;
    
        for (var i = 0; i < numEntries; i++) {
                do {
                        key = generateRandomKey(keyLength);
                } while (key in dict);
                dict[key] = 1;
        }
        return dict;
    }
    
    var dict100 = generateDict(100, 6);
    var arr100 = Object.keys(dict100);
    var searchKey100 = arr100[50];
    
    var dict1000 = generateDict(1000, 6);
    var arr1000 = Object.keys(dict1000);
    var searchKey1000 = arr1000[500];

Test runner

Ready to run.

Testing in
TestOps/sec
lookup key in object of 100 items
if (dict100[searchKey100]);
ready
lookup key in object of 1000 items
if (dict1000[searchKey1000]);
ready
search index of key in array of 100 items
if (arr100.indexOf(searchKey100));
ready
search index of key in array of 1000 items
if (arr1000.indexOf(searchKey1000));
ready

Revisions

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