perf(webui): batch log SSE into ~80ms flushes instead of per-line setState
日志页每收到一条日志就 setLogs(prev => [...prev.filter(id≠), entry].slice(-cap)), 高日志速率下是每条一次 O(n) 过滤+复制 + 一次 React commit。改为入队到 pending、 每 ~80ms 批量 flush:一次 O(n) 合并(Map 去重、last wins)+ 一次 commit。去重(重连 重放同 id)与 maxLines 上限语义保持不变,卸载时 dispose + 清 timer。
This commit is contained in:
1 file changed
+24
-2
@@ -141,9 +141,27 @@ export function LogsPage() {
|
|||||||
}, [api, serverLevel, levelBusy]);
|
}, [api, serverLevel, levelBusy]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
return api.logs.stream({
|
// Batch incoming lines: buffer in a ref and flush on a ~80ms timer instead
|
||||||
|
// of a per-line setState. Under a high log rate this turns N O(n) array
|
||||||
|
// copies + N React commits per window into one. Dedup-by-id and the
|
||||||
|
// maxLines cap are preserved (a reconnect can replay recent ids).
|
||||||
|
let pending: LogEntry[] = [];
|
||||||
|
let flushTimer: number | null = null;
|
||||||
|
const flush = () => {
|
||||||
|
flushTimer = null;
|
||||||
|
if (pending.length === 0) return;
|
||||||
|
const batchMap = new Map(pending.map((e) => [e.id, e] as const));
|
||||||
|
pending = [];
|
||||||
|
setLogs((prev) => {
|
||||||
|
const kept = prev.length ? prev.filter((it) => !batchMap.has(it.id)) : prev;
|
||||||
|
const merged = kept.length ? [...kept, ...batchMap.values()] : [...batchMap.values()];
|
||||||
|
return merged.length > maxLinesRef.current ? merged.slice(-maxLinesRef.current) : merged;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
const dispose = api.logs.stream({
|
||||||
onLine: (entry) => {
|
onLine: (entry) => {
|
||||||
setLogs((prev) => [...prev.filter((it) => it.id !== entry.id), entry].slice(-maxLinesRef.current));
|
pending.push(entry);
|
||||||
|
if (flushTimer == null) flushTimer = window.setTimeout(flush, 80);
|
||||||
},
|
},
|
||||||
onStatus: (s) => {
|
onStatus: (s) => {
|
||||||
if (s === 'open') setStreamStatus('实时');
|
if (s === 'open') setStreamStatus('实时');
|
||||||
@@ -151,6 +169,10 @@ export function LogsPage() {
|
|||||||
else setStreamStatus('已断开');
|
else setStreamStatus('已断开');
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
return () => {
|
||||||
|
dispose();
|
||||||
|
if (flushTimer != null) clearTimeout(flushTimer);
|
||||||
|
};
|
||||||
}, [api]);
|
}, [api]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|||||||
Reference in new issue
Block a user