Performance: Broadcasting to connected clients
This concept affects the responsiveness and scalability of real-time communication by how efficiently messages are sent to multiple clients.
const messageBuffer = Buffer.from(message); clients.forEach(client => { if (client.readyState === WebSocket.OPEN) { client.send(messageBuffer); } });
for (const client of clients) { if (client.readyState === WebSocket.OPEN) { client.send(message); } }
| Pattern | CPU Usage | Event Loop Blocking | Memory Usage | Verdict |
|---|---|---|---|---|
| Sending messages one by one with string conversion | High | High (blocks event loop) | High (many string copies) | [X] Bad |
| Pre-buffering message and sending asynchronously | Low | Low (non-blocking) | Low (single buffer reuse) | [OK] Good |
io.emit.io.emit, which is correct. io.broadcast('message', data); uses a non-existent broadcast method on io. socket.emit('message', data); sends only to one socket. io.send('message', data); uses send which is not the broadcasting method.io.on('connection', (socket) => {
io.emit('news', { hello: 'world' });
});io.emit sends the message to all clients, not just the new one.io.emit broadcasts, every connected client, including the new one, receives the message { hello: 'world' }.io.on('connection', (socket) => {
socket.broadcast.emit('update', { status: 'new' });
});socket.broadcast.emit sends the message to all clients except the one that triggered the event.socket.broadcast.emit, the sender does NOT receive the message, only others do.socket.broadcast.emit.Pass the test and this pattern moves unknown