skip to Main Content

I have ~1Kb dict looking like:

db = {"word": 0, "something": 1, "another": 2, ..., "last": 36000}

and I use the following operations:

  1. find an index of some word (like db["something"]);
  2. find word by its index (like Object.keys($db)[1234])

It works slowly. Would it help if I switch to array?

2

Answers


  1. Chosen as BEST ANSWER

    jsben.ch shows much faster performance with array:

    words = ["word", "something", "another", ..., "last"]
    words_length = words.length;
    random_last_1000 = _.random(1, words_length-1);
    position = words[random_last_1000];
    

    compared with dict:

    words = {"word": 0, "something": 1, "another": 2, ..., "last": 36000}
    words_length = Object.keys(words).length;
    random_last_1000 = _.random(1, words_length-1);
    word_hint = Object.keys(words)[random_last_1000];
    position = words[word_hint];
    

  2. I would say a list of words with length 36000 is not big enough for any optimizations if it is local and in-memory, so just the plain array if it works. Array.prototype.indexOf and Array.prototype.find are surprisingly fast on modern devices.

    If you really need to optimize, in javascript, you may want to use two maps, one is Map<string, number>, the other is Map<number, string>.

    Or you may just use, like, indexedDB, sqlite, Redis, or one of those databases.

    Btw, your implementation to map a number to its word is wrong and it might not always get the correct result on all engines. You should look up the real number instead. Using for...in should slightly improve the speed as well:

    function(n) { for(const k in db) { if(db[k] === n) return k } }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search