Search code examples
javascriptperformanceloopsdictionary

JS: Is using a dictionary faster than looping through an array?


I'm building some program in Nodejs, which will need to keep track in memory of a large number of users. Also, i will have a function that filters a user by id. The code would look something like this:

const users = [
    {
        id: 1,
        name: 'John',
        friends: [3, 6, 8]
    },
    {
        id: 2,
        name: 'Mark',
        friends: [567, 23]
    }
]

function getUserById(userId) {
    const user = users.filter(user => user.id === userId);
    return user[0];
}

The question is, whether this version is generally faster(each key is user id):

const users = {
    1: {
        id: 1,
        name: 'John',
        friends: [3, 6, 8]
    },
    2: {
        id: 2,
        name: 'Mark',
        friends: [567, 23]
    }
}

function getUserById(userId) {
   return users[userId];
}

My intuition says that the dictionary is faster. What are the facts?


Solution

  • Key lookup time in objects is not guaranteed. It might also be O(n), but most engines will optimize it towards O(1) if you dynamically look up a key multiple times. Filtering an array is O(n), .find() however is twice faster on average:

      return users.find(user => user.id === userId);
    

    Now the only datastructure that guarantees O(log n) lookup are Maps:

     const userMap = new Map(users.map(u => [u.id, u]));
     console.log(userMap.get("test"));
    

    If you however plan to do that in a very large scale (100k is large), I would rather move that task to a database, as it is heavily optimized for those tasks. MongoDB would be easy to adopt, Redis would be very fast, there are many others out there.