Performance: ws library for WebSocket server
MEDIUM IMPACT
This affects the server's ability to handle real-time communication efficiently, impacting response time and resource usage.
const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); function broadcast(data, sender) { for (const client of wss.clients) { if (client !== sender && client.readyState === WebSocket.OPEN) { client.send(data); } } } wss.on('connection', ws => { ws.on('message', message => { setImmediate(() => broadcast(message, ws)); }); });
const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', function connection(ws) { ws.on('message', function incoming(message) { wss.clients.forEach(function each(client) { if (client !== ws && client.readyState === WebSocket.OPEN) { client.send(message); } }); }); });
| Pattern | CPU Usage | Event Loop Blocking | Latency | Verdict |
|---|---|---|---|---|
| Synchronous broadcast on message event | High CPU spikes | Blocks event loop | Increased latency under load | [X] Bad |
| Asynchronous broadcast with setImmediate | Balanced CPU usage | Non-blocking event loop | Lower latency and smoother response | [OK] Good |