Performance: Why WebSockets enable real-time features
WebSockets impact the interaction speed between client and server by enabling instant two-way communication, improving responsiveness and user experience.
const socket = new WebSocket('wss://example.com/chat');
socket.onmessage = event => updateUI(JSON.parse(event.data));setInterval(() => fetch('/api/messages').then(res => res.json()).then(updateUI), 3000);
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Polling with HTTP requests | Multiple DOM updates per poll | Triggers reflow each update | Higher paint cost due to frequent updates | [X] Bad |
| WebSocket real-time updates | DOM updates only on new data | Minimal reflows triggered | Lower paint cost with targeted updates | [OK] Good |
@WebSocketGateway().@WebSocketGateway() export class MyGateway {}.@WebSocketGateway()
export class ChatGateway {
@SubscribeMessage('message')
handleMessage(client: any, payload: string): string {
return `Received: ${payload}`;
}
}@WebSocketGateway()
export class MyGateway {
@SubscribeMessage('chat')
handleChat(client, payload) {
client.emit('chat', payload);
}
}client.emit sends message only to that client, but this.server.emit broadcasts to all connected clients.this.server.emit is correct.this.server.emit broadcasts updates instantly to all connected clients efficiently.Pass the test and this pattern moves unknown