import type { MemorySample, Snapshot } from "../shared/ipc";
function escape(text: string): string {
return text.replace(/[&<>"]/g, (char) => {
if (char === "&") return "&";
if (char === "<") return "<";
if (char === ">") return ">";
return """;
});
}
function time(at: number): string {
return new Date(at).toLocaleTimeString("zh-CN", { hour12: false });
}
function mb(value: number): string {
return `${value.toFixed(1)} MB`;
}
function chart(samples: MemorySample[]): string {
if (samples.length < 2) {
return `
采样至少 2 次后绘制趋势。
`;
}
const width = 340;
const height = 84;
const values = samples.map((sample) => sample.totalMb);
const min = Math.min(...values);
const max = Math.max(...values);
const span = Math.max(1, max - min);
const points = samples
.map((sample, index) => {
const x = 8 + (index / (samples.length - 1)) * (width - 16);
const y = height - 10 - ((sample.totalMb - min) / span) * (height - 24);
return `${x.toFixed(1)},${y.toFixed(1)}`;
})
.join(" ");
return `
${min.toFixed(1)}–${max.toFixed(1)} MB · ${samples.length} 个采样
`;
}
export function mountApp(root: HTMLElement): void {
root.innerHTML = `
内存
0 MB 额外分配
主进程 heap—
主进程 RSS—
渲染进程—
总计—
后台节流
两个隐藏窗口分别 backgroundThrottling=true/false,统计 50ms 定时器
触发次数。节流行为依赖平台与窗口状态,本机可能没有差异;不能把它
当作省电保证。
优化清单
- 首帧前只做窗口与最小状态;索引、解析、网络放到首帧后。
- 延迟初始化要能观测:记录开始、完成与耗时。
- commandLine 开关必须在 ready 前追加,ready 后不再生效。
- 泄漏看趋势:多次采样 + heap snapshot,而不是一次数字。
- 隐藏窗口的定时器可能被节流,也可能不会;业务暂停要显式做。
`;
const total = root.querySelector('[data-testid="total"]');
const versions = root.querySelector('[data-testid="versions"]');
const startupTotal = root.querySelector(
'[data-testid="startup-total"]',
);
const stagesEl = root.querySelector('[data-testid="stages"]');
const lazyState = root.querySelector(
'[data-testid="lazy-state"]',
);
const lazyMs = root.querySelector('[data-testid="lazy-ms"]');
const mainHeap = root.querySelector('[data-testid="main-heap"]');
const mainRss = root.querySelector('[data-testid="main-rss"]');
const rendererMem = root.querySelector(
'[data-testid="renderer-mem"]',
);
const totalMem = root.querySelector('[data-testid="total-mem"]');
const allocatedEl = root.querySelector(
'[data-testid="allocated"]',
);
const chartEl = root.querySelector('[data-testid="chart"]');
const heapFile = root.querySelector('[data-testid="heap-file"]');
const processesEl = root.querySelector(
'[data-testid="processes"]',
);
const throttleFacts = root.querySelector(
'[data-testid="throttle-facts"]',
);
const eventsEl = root.querySelector('[data-testid="events"]');
const status = root.querySelector('[data-testid="status"]');
let state: Snapshot | null = null;
let leak: number[][] = [];
let allocatedMb = 0;
function renderStartup(): void {
if (!state) return;
if (total) total.textContent = `${state.startup.totalMs.toFixed(0)} ms`;
if (startupTotal)
startupTotal.textContent = `${state.startup.totalMs.toFixed(0)} ms`;
if (stagesEl) {
const max = Math.max(
1,
...state.startup.stages.map((stage) => stage.deltaMs),
);
stagesEl.innerHTML = state.startup.stages
.map(
(stage) => `
${escape(stage.label)}
${stage.deltaMs.toFixed(1)} ms
`,
)
.join("");
}
if (lazyState) {
lazyState.textContent =
state.startup.lazy.status === "ready"
? "索引已就绪"
: state.startup.lazy.status === "building"
? "索引构建中"
: "等待首帧";
}
if (lazyMs) {
lazyMs.textContent =
state.startup.lazy.status === "ready"
? `${state.startup.lazy.ms} ms`
: "—";
}
}
function renderMemory(): void {
if (!state) return;
const memory = state.memory;
if (mainHeap) mainHeap.textContent = mb(memory.main.heapUsedMb);
if (mainRss) mainRss.textContent = mb(memory.main.rssMb);
if (rendererMem) rendererMem.textContent = mb(memory.rendererMb);
if (totalMem) totalMem.textContent = mb(memory.totalMb);
if (allocatedEl)
allocatedEl.textContent = `${memory.allocatedMb} MB 额外分配`;
if (chartEl) chartEl.innerHTML = chart(memory.samples);
if (heapFile) {
heapFile.textContent = memory.heapSnapshot
? `${memory.heapSnapshot.file} · ${mb(memory.heapSnapshot.bytes / 1024 / 1024)}`
: "";
}
if (processesEl) {
processesEl.innerHTML = `
| 类型 | PID | 工作集 | 峰值 | CPU |
${memory.processes
.map(
(row) => `
| ${escape(row.type)} |
${row.pid} |
${mb(row.workingSetMb)} |
${mb(row.peakMb)} |
${row.cpu}% |
`,
)
.join("")}`;
}
}
function renderThrottle(): void {
if (!throttleFacts || !state) return;
const result = state.throttle;
throttleFacts.innerHTML = result
? `backgroundThrottling=true${result.trueTicks} ticks
backgroundThrottling=false${result.falseTicks} ticks
测量时长${result.durationMs} ms
差异${result.trueTicks === result.falseTicks ? "本机未观察到" : "存在差异"}`
: `尚未运行`;
}
function renderEvents(): void {
if (!eventsEl || !state) return;
eventsEl.innerHTML =
state.events.length === 0
? `暂无活动`
: state.events
.slice(0, 8)
.map(
(row) => `
${time(row.at)}
${escape(row.kind)}
${escape(row.detail)}
`,
)
.join("");
}
function render(next: Snapshot): void {
state = next;
if (versions) {
versions.textContent = `Electron ${next.electronVersion} · Node ${next.nodeVersion}`;
}
renderStartup();
renderMemory();
renderThrottle();
renderEvents();
}
void window.api.perf.snapshot().then(render);
const unsubscribe = window.api.perf.onEvent(() => {
void window.api.perf.snapshot().then(render);
});
requestAnimationFrame(() => {
requestAnimationFrame(() => {
const paint = performance
.getEntriesByType("paint")
.find((entry) => entry.name === "first-paint");
const navigation = performance.getEntriesByType("navigation")[0] as
PerformanceNavigationTiming | undefined;
const firstPaint =
performance.timeOrigin + (paint?.startTime ?? performance.now());
const dcl =
performance.timeOrigin +
(navigation?.domContentLoadedEventEnd ?? performance.now());
void window.api.perf
.reportPaint(firstPaint, dcl)
.then(render)
.catch(() => undefined);
});
});
const allocate = (value: number): void => {
const count = Math.floor((value * 1024 * 1024) / 8);
leak.push(new Array(count).fill(1));
allocatedMb += value;
};
const release = (): void => {
leak = [];
allocatedMb = 0;
};
root
.querySelector('[data-testid="alloc"]')
?.addEventListener("click", async () => {
allocate(24);
render(await window.api.perf.sample(allocatedMb));
});
root
.querySelector('[data-testid="release"]')
?.addEventListener("click", async () => {
release();
render(await window.api.perf.sample(0));
});
root
.querySelector('[data-testid="sample"]')
?.addEventListener("click", async () => {
render(await window.api.perf.sample(allocatedMb));
});
root
.querySelector('[data-testid="heap"]')
?.addEventListener("click", async () => {
render(await window.api.perf.heap());
});
root
.querySelector('[data-testid="lazy-run"]')
?.addEventListener("click", async () => {
render(await window.api.perf.lazy());
});
root
.querySelector('[data-testid="throttle-run"]')
?.addEventListener("click", async () => {
render(await window.api.perf.throttle());
if (status) status.textContent = "节流测试完成";
});
root
.querySelector('[data-testid="refresh"]')
?.addEventListener("click", async () => {
render(await window.api.perf.refresh());
});
const sleep = (value: number): Promise =>
new Promise((resolve) => setTimeout(resolve, value));
window.__prepareShots = async (stage) => {
document.body.dataset.shot = stage;
if (stage === "startup") {
render(await window.api.perf.refresh());
return;
}
if (stage === "memory") {
allocate(24);
render(await window.api.perf.sample(24));
return;
}
release();
render(await window.api.perf.throttle());
await sleep(150);
};
window.__smoke = async () => {
const api = window.api.perf;
const first = await api.snapshot();
await api.sample(0);
allocate(24);
const allocated = await api.sample(24);
release();
await api.sample(0);
const throttleResult = await api.throttle();
await sleep(400);
const final = await api.refresh();
unsubscribe();
return {
startupTotal: first.startup.totalMs,
stageCount: first.startup.stages.length,
firstPaint: first.startup.firstPaintMs,
mainHeap: final.memory.main.heapUsedMb,
rendererMb: final.memory.rendererMb,
processCount: final.memory.processes.length,
sampleCount: final.memory.samples.length,
allocatedMb: allocated.memory.allocatedMb,
trueTicks: throttleResult.throttle?.trueTicks ?? 0,
falseTicks: throttleResult.throttle?.falseTicks ?? 0,
throttleDuration: throttleResult.throttle?.durationMs ?? 0,
lazyMs: final.startup.lazy.ms,
lazyStatus: final.startup.lazy.status,
events: final.events.length,
};
};
}