Performance: Why WebSockets enable real-time communication
HIGH IMPACT
WebSockets impact the interaction responsiveness and reduce network overhead for real-time data exchange.
from fastapi import FastAPI, WebSocket import asyncio app = FastAPI() @app.websocket('/ws') async def websocket_endpoint(websocket: WebSocket): await websocket.accept() for i in range(10): await websocket.send_text(f'{i}') await asyncio.sleep(1) await websocket.close()
import time from fastapi import FastAPI from fastapi.responses import StreamingResponse app = FastAPI() @app.get('/stream') async def stream(): def event_generator(): for i in range(10): yield f'data: {i}\n\n' time.sleep(1) return StreamingResponse(event_generator(), media_type='text/event-stream')
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| HTTP Polling or Streaming | Multiple connections opened/closed | Multiple reflows if UI updates per message | Higher paint cost due to delayed updates | [X] Bad |
| WebSocket Persistent Connection | Single connection maintained | Minimal reflows triggered only on data update | Lower paint cost with instant updates | [OK] Good |