Array indexOf vs. Object key lookup (v6)

Revision 6 of this benchmark created 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] = i;
        }
        return dict;
    }
    
    var dict200000 = generateDict(200000, 4);
    var arr200000 = Object.keys(dict200000);
    var map200000 = new Map(arr200000.map((key,i)=>([key,i])));
    var searchKey100000 = arr200000[100000];

Test runner

Ready to run.

Testing in
TestOps/sec
lookup key in object of 200000 items
if (dict200000[searchKey100000]);
ready
lookup index in array of 200000 items
if (arr200000.indexOf(searchKey100000));
ready
lookup index in Map of 200000 items
if (map200000.get(searchKey100000));
ready

Revisions

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