4
我正在使用NodeJS的WebSocket服务器上工作,我真的需要能够通过套接字和用户的id来查找“类”。双关联数组或1(n)循环更高效?
所以我想弄清楚什么会更有效率,为什么。
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(..);
我倾向于第一种选择,但我不知道JavaScript的手柄究竟是如何存储的值,如果值的每个“关联数组”专卖店,而不是由参考,这是一个完整的浪费。我特别不想迷恋记忆复制。
对象值**总是**引用。 – Pointy
@Pointy - 我只需要知道;)。 – Hobbyist
我不认为你在第二个版本中写了你的意思。它应该不是'for(客户端在用户){如果(用户[客户端] .userid == id)...}'? – Barmar