Is a double associative array or 1 (n) loop more efficient?

I work on a WebSocket server using NodeJS, and I really need to be able to search for the "class" of both the socket and the user ID.

So, I'm trying to figure out what will be more effective and why.

var usersBySocket = {};
var usersById = {}

// ID is pulled from database in NetworkClient constructor.
server.on('connection', function(client) {
    var networkClient = new NetworkClient(client);
    usersBySocket[client] = networkClient;
    usersById[networkClient.getId()] = networkClient;
});

// When needing to send a specific user some data
// based on his user id (IE: Messaging).
// usersById(...).send(...);

OR

var users = {}

server.on('connection', function(client) {
    users[client] = new NetworkClient(socket);
});

function getUserById(id) {
    for(var uid in users) {
        if(uid == id) return users[uid];
    } 
    return undefined;
}

// Then when I needto use it, call it like so:
// getUserById(..).getSocket().send(..);

I am inclined to the first option, but I'm not sure how exactly JavaScript handles values, if each "associative array" is stored by value, and not by reference, this is a complete waste. I especially do not want an obsessive copy of memory.

+4
source share
1 answer

Objects are stored by reference. But the first option will always use more memory for the object usersById.

, , , .

0

Source: https://habr.com/ru/post/1612502/


All Articles