Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 双关联数组或1(n)循环更有效?_Javascript - Fatal编程技术网

Javascript 双关联数组或1(n)循环更有效?

Javascript 双关联数组或1(n)循环更有效?,javascript,Javascript,我正在使用NodeJS在WebSocket服务器上工作,我真的需要能够通过套接字和用户id查找“类” 所以我想知道什么更有效率,为什么 var usersBySocket = {}; var usersById = {} // ID is pulled from database in NetworkClient constructor. server.on('connection', function(client) { var networkClient = new Network

我正在使用NodeJS在WebSocket服务器上工作,我真的需要能够通过套接字和用户id查找“类”

所以我想知道什么更有效率,为什么

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(...);


我倾向于第一个选项,但我不确定JavaScript是如何处理存储值的,如果每个“关联数组”都是按值而不是按引用存储,那就完全是浪费。我特别不想要强迫性的记忆拷贝

对象通过引用存储。但是第一个选项总是为
usersById
对象使用更多内存


第二个选项使用更少的内存,但您试图进行线性搜索以找到具有正确id的用户,这是无效的。

对象值始终是引用。@Pointy-我需要知道的全部;)。我认为你在第二个版本中没有写下你的意思。(用户中的客户端){if(users[client].userid==id)}不应该是
?它们都没有多大意义?第一个将同一个函数实例存储在两个对象中,第二个使用循环来执行只需
users[id]
而不是函数即可完成的操作?只需将连接存储在一个对象中,客户机作为键,然后使用一个简单的map对象,ID作为键,ClientId作为值,这似乎更简单。
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(..);