《Electron 45.2.3 内核解剖》第 23 章 性能:启动、内存与进程指标
23.0 五条边界,和一张「性能」的分解图
前面 22 章里,"性能"这个词一直以副产品身份出现:第 3 章讲 380 个补丁时提过 v8_enable_private_mapping_fork_optimization,第 8 章讲七个 bundle 时提过构建期 code cache,第 12 章讲 preload 时提过同步 IPC 的代价,第 14 章讲 invoke 时提过一次序列化的开销,第 22 章讲 asar 时提过 Windows 上归档能减少文件打开次数。这些都是散落的点。这一章把它们收成一条线,并且补上前面没有正面处理过的另一半:Electron 到底提供了哪些可观测手段,以及这些手段自身有多可信。
先钉死一个前提:性能不是一个数。一个 Electron 应用"慢",可能是三件互不相干的事:
| 问题域 | 典型提问 | 计量单位 | 主要证据源 |
|---|---|---|---|
| 冷启动延迟 | 双击图标到窗口出现要多久 | 墙钟毫秒、主线程阻塞时长 | --trace-startup、V8 快照、bundle 加载链 |
| 稳态资源占用 | Idle 时为什么占 400 MB / 8% CPU | KB、百分比、每秒唤醒次数 | app.getAppMetrics()、process.*、getTraceBufferUsage |
| 可观测性本身 | 我量到的这个数到底代表什么 | 采样区间、口径、平台差异 | 本章 23.6–23.10 的源码 |
这三件事经常被混为一谈,然后得出错误结论。比如把 app.getAppMetrics() 返回的 percentCPUUsage 当作"当前 CPU 占用率"画成实时曲线——它是自上次调用以来的平均值,调用频率直接改变读数(23.7.3);又比如用 performance.now() 在 app.whenReady() 里测启动时间——那时用户主脚本已经跑完了,测到的是 JS 执行耗时,不是进程启动耗时(23.1.6)。
再钉死五条边界。本章几乎每一个反直觉结论都能归到其中一条:
| 边界 | 两侧 | 关键判据 |
|---|---|---|
| ① 构建期 / 运行期 | node_mksnapshot、js2c code cache vs JavascriptEnvironment | 省掉的运行期工作,是在构建机上付过的 |
| ② 浏览器进程 / 渲染器进程 | GetExtraCreateNewWindowReplyData vs SetStartupData | 同一份启动数据,一侧序列化、一侧反序列化 |
| ③ 采集 / 上报 | MetricsService 对象存在 vs ERR_NOT_IMPLEMENTED | 有采集代码不等于有遥测 |
| ④ Chromium 原语 / Electron 包装 | base::ProcessMetrics vs ProcessMetric | Electron 只做平台内存读取与字典拼装 |
| ⑤ 官方建议 / 源码事实 | performance.md 八条 vs 实际实现 | 建议是启发式的,实现是可以逐条核对的 |
按这五条边界,把本章涉及的设施摊开:
| 设施 | 所在层 | 解决什么 | 本章位置 |
|---|---|---|---|
| V8 context snapshot / Node startup snapshot | 构建期 + shell/app | 免去堆初始化与 Node bootstrap 重编译 | 23.2 |
js2c code cache / CompileBundle | 构建期 + shell/common | 免去内部 bundle 的源码编译 | 23.3 |
RendererStartupData 预推 | 浏览器进程 → 渲染器 | 免去 preload 的同步 IPC 与首次编译 | 23.4 |
ProcessMetric / getAppMetrics() | 浏览器进程 | 全进程树的 CPU/内存快照 | 23.6–23.7 |
ElectronBindings::BindProcess | 全进程 | 单进程的 V8 堆/Blink 堆/系统内存 | 23.8 |
contentTracing | 浏览器进程 | Perfetto trace 会话 | 23.9 |
| Node → Chromium Perfetto 十个补丁 | Node / V8 / Chromium | 让 node.* 事件汇入同一份 trace | 23.10 |
--trace-startup / --profile-electron-init | Chromium / bundle | 测量启动本身 | 23.11 |
| OOM 双路径与 crash keys | V8 + 渲染器 | 堆耗尽时留下可诊断信息 | 23.12 |
backgroundThrottling 与 compositor | 浏览器进程 + Chromium 补丁 | 后台窗口的帧与定时器 | 23.13 |
ElectronMetricsServiceClient | 浏览器进程 | 只给 trace 填元数据,不上报 | 23.14 |
有一条取证原则要写在前头,因为它决定了本章很多段落的写法:"仓库里没有"也是一条可验证的结论,而且往往比"有"更有信息量。比如全仓库 shell/ 下没有任何主进程启动耗时的 base::TimeTicks 打点,没有 UMA_HISTOGRAM_TIMES,没有 StartupTimer;shell/browser/metrics/ 下确实有一个 metrics::MetricsService 实例,但 IsConsentGiven() 恒为 false、上传间隔是 FiniteMax()、uploader 恒返回 ERR_NOT_IMPLEMENTED;--disable-background-timer-throttling 这个在社区里被反复推荐的开关,在本仓库(含 patches/)零命中。这些"没有"必须写明,否则读者会按不存在的机制去调优。本章凡是给出"未找到"的地方,都会附上检索过的关键词,方便复核。
另外,本树是 Electron 45.2.3 加 2026 年补丁集:renderer_startup_data.* 的预推已取代旧同步 IPC handler,node_use_node_snapshot 是重新启用而非「一直开启」,bundler 已换成 rolldown,OOM 不再是单一 OnOOM 路径。第 22 章预告的「逐项量化」也要修正:Electron 没有逐项耗时的打点,本章只讲清每项优化的源文件与代价边界,方法在 23.16,不虚构毫秒数。
23.1 从可执行文件到 app ready:一条没有计时的时间轴
23.1.1 入口处的第一次分叉:ELECTRON_RUN_AS_NODE
理解启动耗时的第一步,是承认有些"启动"根本不启动 Chromium。三个平台的入口文件都先检查同一个环境变量:
electron_main_win.cc:153-164
bool run_as_node =
electron::fuses::IsRunAsNodeEnabled() && IsEnvSet(electron::kRunAsNode);
// Make sure the output is printed to console.
if (run_as_node || !IsEnvSet("ELECTRON_NO_ATTACH_CONSOLE"))
base::RouteStdioToConsole(false);
if (run_as_node) {
base::AtExitManager atexit_manager;
base::i18n::InitializeICU();
return electron::NodeMain();
}
Linux 在 electron_main_linux.cc:55、macOS 在 electron_main_mac.cc:73 有同一处短路。注意判据是两个条件的合取:process_util.cc:43-47 的 IsRunningAsNode() 先用 fuses::IsRunAsNodeEnabled() 过一道 fuse,再查环境变量,且结果用 static bool 缓存。也就是说 runAsNode fuse 被翻转后,ELECTRON_RUN_AS_NODE 会被完全忽略(environment-variables.md:107 明说了这一点)。这条短路的意义不只是"把 Electron 当 node 用"——lib/node/init.ts:35、:43、:55 显示 child_process.fork 会自动设置这个变量,于是所有从主进程 fork 出去的 Node 子进程走的是纯 Node 启动路径,不付 Chromium 初始化的代价。
这也是一个容易被误读的性能结论:看到 app.getAppMetrics() 里某个子进程 CPU 很低,先要确认它是不是根本没跑 Chromium。
23.1.2 BasicStartupComplete:最早能干预的位置
进入 Chromium 启动后,第一个 Electron 钩子是 ElectronMainDelegate::BasicStartupComplete()(electron_main_delegate.cc:177-245)。与性能直接相关的三行在 :191-200:
// Enable convenient stack printing. This is enabled by default in
// non-official builds.
if (env->HasVar(kElectronEnableStackDumping))
base::debug::EnableInProcessStackDumping();
if (env->HasVar(kElectronDisableSandbox))
command_line->AppendSwitch(sandbox::policy::switches::kNoSandbox);
tracing_sampler_profiler_ =
tracing::TracingSamplerProfiler::CreateOnMainThread();
最后一行是整条启动链上唯一的采样器挂载。TracingSamplerProfiler 本身不计时,它给后续的 Perfetto trace 提供栈采样能力。这里的位置很关键:它在 chrome::RegisterPathProvider()(:202)之前,也就是进程刚能读命令行、还没有路径服务、没有 ICU 资源包的时候。
command-line-switches.md:5-7 要求 app.commandLine.appendSwitch() 必须在 ready 事件之前调用,原因就在这条链上:Chromium 的很多 feature 在 BasicStartupComplete 到 PreBrowserMain 之间读取命令行并固化,JS 侧的 appendSwitch 一旦晚于这个窗口,改的是同一份 base::CommandLine 对象,但读者已经读过了。--js-flags 是文档里唯一明确标注"必须在启动时传入才能在主进程生效"的开关(:137-140)。
command-line-switches.md:395-401 还列了一条与启动延迟直接相关的 Chromium feature:
SpareRendererForSitePerProcess— keeps a spare renderer process running at all times so that a new window does not wait for a process to launch
这是典型的用常驻内存换窗口创建延迟。spec/api-web-contents.spec.ts:2575-2603 正是用 app.getAppMetrics().filter(m => m.type === 'Tab').map(m => m.pid) 追踪这个 spare renderer 的 pid 变化——一个把 23.6 的指标 API 反过来用于验证进程模型的例子。
23.1.3 PreSandboxStartup 与 PreBrowserMain 的时序约束
PreSandboxStartup()(:247-338)里几条与启动路径相关的分叉:
:266-268logging::InitElectronLogging(... is_preinit = IsBrowserProcess() || IsZygoteProcess()),主进程在此建立日志;:275-281LoadResourceBundle()只对子进程执行,主进程不需要;:283-298crashpad 的初始化时机在两类进程里不同:子进程立即初始化,主进程要等 JS 侧调用crashReporter.start()。源码注释(:284-286)写得很直接——"wait for JS"。这既是第 20 章讲崩溃报告时提到的可配置性来源,也意味着主进程启动早期的一段窗口不在 crashpad 覆盖下;:318-337仅浏览器进程追加开关,并执行ui::OzonePlatform::PreSandboxStartup()。
PreBrowserMain()(:347-371)的三步有严格顺序,注释(:348-350)标为时序约束:
FieldTrialList → InitializeFeatureList() → content::InitializeMojoCore()
紧随其后的 PostEarlyInitialization() 调 InitializeMemorySystem(),注释(:375)是 "Start memory observation as early as possible"。这一行是本章 23.8 那些内存 API 能拿到数据的前提——但要注意它初始化的是 Chromium 的 memory instrumentation,不是 OS 级监控。
fuses.md:86 提到的 embeddedAsarIntegrityValidation 会 "marginally slow down file reads from inside the app.asar archive",代价就落在这之后的所有归档读取上;第 22 章讲过 asar integrity 的三级信任链,那是安全性,这里补上它的性能侧:校验是每次读块都算 SHA256,不是启动时校验一次。
23.1.4 ElectronBrowserMainParts:Node 与 V8 环境在这里合流
构造函数的四个成员(electron_browser_main_parts.cc:202-212)几乎就是第 6 章那张图的压缩版:
ElectronBrowserMainParts::ElectronBrowserMainParts()
: fake_browser_process_(std::make_unique<BrowserProcessImpl>()),
node_bindings_{
NodeBindings::Create(NodeBindings::BrowserEnvironment::kBrowser,
uv_default_loop())},
electron_bindings_{
std::make_unique<ElectronBindings>(node_bindings_->uv_loop())},
browser_{std::make_unique<Browser>()} {
DCHECK(!self_) << "Cannot have two ElectronBrowserMainParts";
self_ = this;
}
BrowserProcessImpl 是给 Chromium 看的假 BrowserProcess(第 2 章讲进程模型时展开过),NodeBindings 持有 libuv 默认循环,ElectronBindings 就是 23.8 里往 process 上挂方法的那个类,Browser 是平台事件源。
真正的 V8 / Node 环境建立在 :300-345。其中 :302-310 的 trap handler 必须在建 isolate 之前启用;:314 创建 JavascriptEnvironment;:319-324 是本版本最值得注意的一段:
electron_browser_main_parts.cc:322-323
// Electron: when the embedded Node startup snapshot is being consumed,
// JavascriptEnvironment did not create a context (it comes from
// Context::FromSnapshot inside node::CreateEnvironment) -- pass empty.
v8::Local<v8::Context> context = isolate->GetCurrentContext();
node_bindings_->Initialize(isolate, context);
这句注释是 23.2 全部内容的引子:当嵌入式 Node 启动快照被消费时,V8 context 不是 Electron 创建的,而是从快照里反序列化出来的,所以传给 node_bindings_->Initialize() 的 context 可以为空。理解这一点,才能理解为什么自定义 V8 快照会让 Electron 放弃 Node 启动快照。
23.1.5 Linux 上的 FontConfig 并行化:一处真正的时间轴优化
:326-335 是本树里少见的一处、明确以"把工作挪出主线程关键路径"为目的的代码:
electron_browser_main_parts.cc:329-332
#if BUILDFLAG(IS_LINUX)
// Runs during Node.js environment creation and is joined before any app
// code can run, so nothing else touches FontConfig or the environment.
const auto fontconfig_env = SnapshotFontConfigEnv();
// If the thread cannot be created the handle stays null, the join is a
// no-op and GTK initializes FontConfig itself as before.
static base::NoDestructor<SystemFontConfigInit> system_fontconfig_init;
base::PlatformThread::Create(0, system_fontconfig_init.get(),
&system_fontconfig_thread_);
#endif
FcInit() 在冷启动时要扫字体目录、建缓存,可能占用几十到上百毫秒。这里的做法是在 Node 环境创建期间起一个后台线程去做,然后在 JoinSystemFontConfigInit()(:590-597)等待——但等待点被放在用户代码能运行之前、并且尽可能晚。注释里 three 个细节值得逐条读:
- "during Node.js environment creation" —— 并行窗口与 Node 环境初始化重叠;
- "joined before any app code can run, so nothing else touches FontConfig or the environment" —— 说明为什么可以安全并行:FontConfig 不是线程安全的,所以必须保证在它完成前没有别人碰;
SnapshotFontConfigEnv()—— 把当前环境变量快照给后台线程,避免后台线程与主线程同时读写environ。
第三条与 renderer_startup_data.cc:35-52 的 CaptureBrowserEnvironment() 是同一类防护,只是方向相反(一个是给后台线程一份只读副本,一个是给子进程一份序列化副本)。线程创建失败时句柄保持为空,join 变成 no-op,GTK 回退到自己初始化——这是一个有明确降级路径的优化,不是无条件假设。
23.1.6 PreMainMessageLoopRun:用户 main 脚本的准确位置
electron_browser_main_parts.cc:600-604
int ElectronBrowserMainParts::PreMainMessageLoopRun() {
// Run user's main script before most things get initialized, so we can have
// a chance to setup everything.
node_bindings_->PrepareEmbedThread();
node_bindings_->StartPolling();
PrepareEmbedThread() + StartPolling() 是第 6 章"两个事件循环的婚姻"里那条把 libuv 嵌进 Chromium 消息泵的链路。注释直说了设计意图:用户主脚本跑在"大部分东西还没初始化"的时候,这样用户才有机会配置它们。:644-653 依次调 fake_browser_process_->PreMainMessageLoopRun()、Browser::DidFinishLaunching()、Browser::PreMainMessageLoopRun()。
这条时序解释了两件事:
- 为什么
app.whenReady()的 Promise 兑现不等于"启动完成"——ready 是 Chromium 初始化到某个程度的信号,用户脚本在此之前就已经在执行; - 为什么在
app.whenReady()里用performance.now()测不出启动耗时——performance.now()的起点是 JS 环境建立,而在此之前已经走完了入口分叉、BasicStartupComplete、快照反序列化、FontConfig 等待等全部 native 阶段。
要测冷启动,只能从进程外(父进程计时、ETW、--trace-startup)或从 Chromium 最早期的 trace 事件算起,见 23.11。
PostCreateMainMessageLoop()(:670-690)里还有一条时序依赖注释(:684-686):os_crypt::Config 必须在网络服务启动之前完成。PreCreateMainMessageLoop()(:769-788)做 Mac 的 InitializeMainNib() / RegisterURLHandler()、Windows 的 OSCrypt::Init 等。这些都是"用户脚本无法干预"的段落。
23.1.7 lib/browser/init.ts:app ready 之前 JS 侧做了什么
lib/browser/init.ts 只有 121 行,却决定了 JS 启动路径上的全部固定开销。按行号顺序:
| 行号 | 动作 | 性能含义 |
|---|---|---|
:7 | const Module = require('module') | 最早的一次内置模块加载 |
:10 | require('@electron/internal/common/init') | 包装定时器、Module._resolveFilename,见 23.3.4 |
:12 | setEventEmitterPrototype(EventEmitter.prototype) | 让 C++ 侧事件对象继承 JS 的 EventEmitter |
:15-31 | uncaughtException 处理器里懒加载 require('electron') | 注释明说不能在顶部 import,因为本文件负责建立 require hook |
:34-38 | require('electron') 取 app,注册 quit → process.emit('exit') | 第一次真正取到 app |
:42-50 | 覆写 process.exit → app.exit() | 保证 Chromium 正常退出 |
:52-59 | ipc-dispatch、rpc-server、guest-view-manager 三次 require | 固定开销 |
:61-72 | 从 getHiddenValue(global, 'appPackage') 取 C++ 已解析的 package.json | 不重新读盘、不重新解析 JSON |
:74 | app.setAppPath(appPackage.path) | |
:76-86 | 预加载 protocol、service-worker-main、web-contents、web-frame-main | 注释:"ensure it is populated on app ready" |
:89-93 | 注册 window-all-closed 默认退出 | |
:95-101 | 取出并删除 process.appCodeLoaded;应用 appPackage.v8Flags | 见下文 |
:103-121 | ESM/CJS 分发入口脚本,appCodeLoaded!() | 用户代码从这里开始 |
:95-101 是整章最容易被忽略、也最能说明"启动优化如何约束代码顺序"的一段:
lib/browser/init.ts:95-98
const { appCodeLoaded } = process;
delete process.appCodeLoaded;
// Applied only now so that everything above still matched its code cache.
if (appPackage.v8Flags) {
(require('v8') as typeof v8).setFlagsFromString(appPackage.v8Flags);
}
V8 的 flag 会改变 code cache 的兼容性判据。如果 package.json 里配了 v8Flags,Electron 故意把它推迟到内部 bundle 全部加载完之后才应用,注释给出的理由是"让上面那些代码仍然命中它的 code cache"。这是一处真实的顺序约束:把 setFlagsFromString 往上挪一行,可能让整个内部 bundle 的构建期 code cache 全部失效,退化成源码编译。第 22 章讲 ValidateV8Snapshot 时说过构建期哈希是信任锚,这里是同一思想的另一面——构建期产物的有效性依赖运行期的执行顺序。
:61-72 的 getHiddenValue(global, 'appPackage') 也值得和第 5 章对照:C++ 在更早就解析了 package.json(app_package.cc),JS 侧只取隐藏值,避免了第二次文件读取与 JSON 解析。这也是为什么第 22 章说 asar 的 retained fd 与 header 缓存对启动路径影响很大——package.json 就在归档里。
23.1.8 一条必须写明的负面结论:Electron 没有启动耗时打点
对 shell/ 全目录检索 TimeTicks、StartupTimer、UMA_HISTOGRAM_TIMES、TRACE_EVENT.*[Ss]tartup、startup_time、ScopedUmaHistogramTimer:命中的 TimeTicks 全部与网络超时、UI 动画、拖拽区域调试有关(例如 electron_api_url_loader.cc:980、asar_url_loader.cc:127-128、draggable_region_debugger.cc:82),没有一处用于主进程启动计时。shell/app/ 下 TRACE_EVENT 相关命中只有 electron_main_delegate.cc:200、.h:17、.h:72 三处 TracingSamplerProfiler;electron_browser_main_parts.cc:513 只有 :513 的子线程采样器。
也就是说:Electron 45.2.3 不提供「启动耗时」这个指标。官方只推荐 Chrome Tracing;启动路径横跨 Node、Chromium content、Blink、平台 UI 四套代码,任何单点计时都会漏掉大半,所以正确做法是把各家的 trace 事件汇进同一条 Perfetto 时间线(23.9–23.11)。
23.1.9 时间轴上的可干预点
把上面八节收成一张表。这张表的用途是:当你想优化冷启动时,先确认你要动的是哪一段,以及那段是否受应用代码控制。
| 阶段 | 入口 | 主要工作 | 应用能否干预 | 相关机制 |
|---|---|---|---|---|
| 0 | electron_main_*.cc | 环境变量分叉 | 能(fuse / 环境变量) | ELECTRON_RUN_AS_NODE、runAsNode fuse |
| 1 | BasicStartupComplete | 日志、sandbox、采样器、路径 | 能(命令行开关) | --js-flags、feature 开关 |
| 2 | PreSandboxStartup | 资源包、crashpad、Ozone | 基本不能 | crashReporter.start 时机 |
| 3 | PreBrowserMain | FieldTrial → FeatureList → Mojo | 不能 | InitializeMemorySystem |
| 4 | JavascriptEnvironment | 快照反序列化、isolate | 能(fuse / 自定义快照) | 23.2 |
| 5 | CreateEnvironment | Node bootstrap | 能(是否走 Node 快照) | 23.2.6 |
| 6 | Linux FontConfig 线程 | 字体缓存 | 不能 | join 点在用户代码前 |
| 7 | common/init + bundle | 定时器包装、模块加载 | 不能 | 23.3 |
| 8 | lib/browser/init.ts | 注册、预加载四个模块 | 不能 | 23.1.7 |
| 9 | PreMainMessageLoopRun | 用户 main 脚本 | 完全由应用决定 | performance.md 八条建议 |
| 10 | app.whenReady() | 建窗口、加载页面 | 完全由应用决定 | 23.4 / 23.13 |
阶段 9 和 10 是应用开发者真正能优化的部分,官方文档的八条建议(23.5)几乎全部落在这里;能改的是自己的 require() 图和建窗时机。
23.2 V8 启动快照:把堆初始化搬到构建机上
23.2.1 先分清两个都叫 snapshot 的东西
这一节最容易出的错,是把下面两件东西当成一个:
| V8 context snapshot | Node startup snapshot | |
|---|---|---|
| 文件 | v8_context_snapshot.bin / browser_v8_context_snapshot.bin | 编进二进制的 node::SnapshotData |
| 生成者 | mksnapshot / v8_context_snapshot_generator | node_mksnapshot(host tool) |
| 内容 | V8 内置对象的只读堆 | 已 bootstrap 的 Node.js 环境 |
| 谁消费 | 所有进程(按 fuse 分文件) | 浏览器进程、utility 进程、ELECTRON_RUN_AS_NODE 子进程 |
| 选择逻辑 | GetBrowserV8SnapshotFilename() | NodeSnapshotForThisProcess() |
| 校验 | ValidateV8Snapshot() 比 SHA256 | 与 V8 快照共用 fuse |
electron_main_delegate.cc:398-406 是前者的选择点:
std::string_view ElectronMainDelegate::GetBrowserV8SnapshotFilename() {
bool load_browser_process_specific_v8_snapshot =
IsBrowserProcess() &&
electron::fuses::IsLoadBrowserProcessSpecificV8SnapshotEnabled();
if (load_browser_process_specific_v8_snapshot) {
return "browser_v8_context_snapshot.bin";
}
return ContentMainDelegate::GetBrowserV8SnapshotFilename();
}
后者在 javascript_environment.cc:134-168 的 NodeSnapshotForThisProcess(),返回 const node::SnapshotData*。两者会互相影响——这正是 23.2.7 要讲的性能反噬。
BUILD.gn:1232-1240 说明前者如何随包分发:在 v8_use_external_startup_data 打开时,bundle_data 里加入 $root_out_dir/snapshot_blob.bin 或 $v8_context_snapshot_filename;:602-604 则在 v8_use_external_startup_data && use_v8_context_snapshot && current_toolchain == default_toolchain 时加 :mksnapshot_checksum_gen 依赖。注意 use_v8_snapshot / v8_use_snapshot 这两个名字在本仓库零命中,v8_use_external_startup_data 是上游 V8 定义的 declare_args(),Electron 只消费;node_use_node_snapshot 定义在 Node 补丁改过的 node.gni 里,不在本树的 .gn 文件中。写构建脚本或查配置时按错名字会一无所获。
23.2.2 node_use_node_snapshot 是"重新启用"的
electron_enable_node_startup_snapshot_generation_in_chromium_s_v8.patch:4-7 共 576 行,主题行(:4-8)就把历史讲清楚了:
Subject: electron: enable node startup snapshot generation in Chromium's V8
Re-enable node_use_node_snapshot so node_mksnapshot generates an embedded
Node startup snapshot the Electron browser process can be created from,
eliminating the Node bootstrap recompile.
补丁对 node.gni 的改动(:86-108)删掉了上游那段以开发者注记开头的禁用注释(原文列举了若干尚未解决的问题),把两个开关绑到同一个条件:
# Embed a startup snapshot of the bootstrapped Node.js environment, and the
# V8 code cache for the builtins that complements it, to speed up startup.
node_use_node_snapshot = node_snapshot_toolchain_runs_target_code
node_use_node_code_cache = node_snapshot_toolchain_runs_target_code
上游原本把 node_use_node_code_cache 定义为 host_os == target_os && host_cpu == target_cpu(交叉编译时关闭)。新条件 node_snapshot_toolchain_runs_target_code 的含义是:生成快照的那套 toolchain 必须能跑目标架构的代码。这比单纯比较 host/target 更精确——快照是目标架构的内存布局,生成它的进程必须真能执行那种代码。
这条补丁买到的东西是:浏览器进程的 Node 环境不再从源码 bootstrap。BUILD.gn:1003 的 node_builtins = !node_use_node_snapshot 是同一枚硬币的背面——有了快照就不需要把 Node 内建模块的源码再编进二进制。
23.2.3 为什么必须 extend 一份已有快照
补丁里最关键、也最容易被跳过的一段在 embed_helpers.cc(:120-127):
// Electron: extend an existing V8 startup snapshot rather than build the
// heap from scratch (Electron's V8 has external startup data / the
// deserialize-only setup-isolate delegate, so InitWithoutSnapshot
// aborts). nullptr -> upstream from-scratch behavior.
if (const v8::StartupData* base =
SnapshotBuilder::GetBaseSnapshotForCreation()) {
params.snapshot_blob = const_cast<v8::StartupData*>(base);
}
上游 Node 的 node_mksnapshot 是从空堆开始 SnapshotCreator::Create 的。在 Electron 里这条路走不通,注释给了两个原因:Electron 的 V8 带 external startup data,以及 setup-isolate delegate 是 deserialize-only 的,调 InitWithoutSnapshot 会直接 abort。所以 Electron 的做法是在 Chromium 的 V8 context snapshot 之上再叠一层 Node 快照。
配套的三处改动:
:198-214node_snapshot_builder.h新增SetBaseSnapshotForCreation/GetBaseSnapshotForCreation,注释点明这与v8_context_snapshot_generator同构;:240-259node_snapshotable.cc实现g_base_snapshot_for_creation这个全局指针;:264-315tools/snapshot/node_mksnapshot.cc新增--electron-v8-snapshot-blob=<path>参数,读出 blob 后调用 setter。
于是构建期的依赖链是:先由 V8 的 mksnapshot 产出 snapshot_blob.bin,再把这份 blob 喂给 node_mksnapshot,生成 Node 快照。BUILD.gn:443-484 的 run_node_mksnapshot action 里能看到这个参数(:480-481):
args += [
"--electron-v8-snapshot-blob",
rebase_path("$root_out_dir/snapshot_blob.bin", root_build_dir),
]
:469-473 还有一段关于 V8 flags hash 对齐的注释:生成快照时用的 V8 flag 必须与消费快照时一致,否则 code cache / 只读堆布局对不上。这与 23.1.7 里 v8Flags 被推迟应用是同一个约束的两种表现。
另外一个容易漏掉的构建细节在 :386-424:node_mksnapshot 这个 host tool 依赖 "$node_v8_path:external_startup_data"(:407),并用 zstd:compress。也就是说快照内容在编进二进制前是压缩的。
23.2.4 code cache 的合并,而不是替换
:132-157 改了 node_builtins.cc 的 RefreshCodeCache,把"替换"语义改成 merge + insert_or_assign。原因不难推:Node 快照自带一份内建模块的 code cache,构建期 js2c 又会产出另一份(针对 Electron 自己的 bundle),如果后者直接覆盖前者,快照里那些内建模块的缓存就丢了,反而变慢。
:159-177 顺手修了 node_constants.cc 的 NODE_SNAPSHOT_TARGET_LINUX_ARM 常量——交叉编译到 Linux ARM 时 O_* 常量值不同,从 host 生成的快照里读出的文件打开标志会错。这类补丁看似与性能无关,但它是"快照能在目标架构上正确工作"的前提。
:320-348 的 unofficial.gni 把 NODE_USE_V8_PLATFORM 定义为 node_use_v8_platform || node_use_node_snapshot;:492-573 把 node_snapshot / node_snapshot_stub 拆成两个 source_set 并用强符号,避开 Windows lld-link 的弱符号重复定义问题。这些都是把同一个优化搬上四个平台所需的工程代价,说明书里不会写。
23.2.5 ValidateV8Snapshot:安全 fuse 顺带管住了快照
electron_main_delegate.cc:126-138:
void ValidateV8Snapshot(v8::StartupData* data) {
if (data->data &&
electron::fuses::IsEmbeddedAsarIntegrityValidationEnabled()) {
CHECK_GT(data->raw_size, 0);
UNSAFE_BUFFERS({
base::span<const char> span_data(
data->data, static_cast<unsigned long>(data->raw_size));
CHECK(base::ToLowerASCII(base::HexEncode(
crypto::hash::Sha256(base::as_bytes(span_data)))) ==
electron::snapshot_checksum::kChecksum);
})
}
}
注册在构造函数里(:163-165):
electron_main_delegate.cc:163-164
ElectronMainDelegate::ElectronMainDelegate() {
gin::SetV8SnapshotValidator(base::BindRepeating(&ValidateV8Snapshot));
}
kChecksum 来自 BUILD.gn:1104-1115 的 mksnapshot_checksum_gen target 生成的 snapshot_checksum.h。
第 22 章 22.5 讲 asar integrity 时已经指出一个反直觉耦合:开启 asar 完整性校验 fuse 会顺带锁死 V8 快照的哈希。这里补上性能侧的含义:CHECK 的是整份 blob 的 SHA256,在反序列化之前执行,属于阶段 4 的固定开销。对一个几十 MB 的快照,这次哈希不是免费的。换自定义 V8 快照(用 electron-mksnapshot 生成)必须同时重新编译以更新 checksum,否则进程在极早期直接 CHECK 失败——这类失败往往表现为"双击无反应",连日志都来不及初始化。
fuses.md:86 说的 "marginally slow down file reads" 与这里的哈希是两笔不同的开销,不要合并计算。
23.2.6 哪些进程真正吃到 Node 快照,以及回退条件
javascript_environment.cc:114-168 是判定逻辑。先定义"内置快照":
// Whether the V8 snapshot blob this process loaded (v8_context_snapshot.bin,
// or in the browser process under the LoadBrowserProcessSpecificV8Snapshot
// fuse, browser_v8_context_snapshot.bin) is the one this build shipped ...
bool LoadedV8SnapshotIsBuiltIn() { ... }
再选出当前进程可用的 Node 快照(:134-168,节选):
javascript_environment.cc:144-151
// The Node startup snapshot a JavascriptEnvironment's isolate is created
// from, when one is embedded and this process is allowed to consume it: the
// browser process, ELECTRON_RUN_AS_NODE children ... and the utility process ...
const node::SnapshotData* NodeSnapshotForThisProcess() {
static const node::SnapshotData* const snapshot =
[]() -> const node::SnapshotData* {
if (!electron::IsBrowserProcess() && !electron::IsUtilityProcess())
return nullptr;
const node::SnapshotData* embedded =
node::SnapshotBuilder::GetEmbeddedSnapshotData();
...
if (!LoadedV8SnapshotIsBuiltIn()) {
VLOG(1) << "Custom V8 snapshot loaded; not creating this process's "
"Node.js environment from the embedded Node snapshot.";
三条判据:
- 进程类型:只有浏览器进程和 utility 进程能消费;渲染器进程不消费。这与第 16 章讲 utility process 时的结论一致——utility 进程是"带 Node 但不带 Chromium UI 的浏览器进程",因此共享这条启动路径。
- 嵌入式快照存在:
GetEmbeddedSnapshotData()返回非空。 - V8 快照必须是本构建自带的那份:
LoadedV8SnapshotIsBuiltIn()为假时返回nullptr,并留一条VLOG(1)。
第 3 条是整套机制最微妙的地方。为什么自定义 V8 快照就要放弃 Node 快照?因为 Node 快照是在构建期那份 V8 context snapshot 之上叠加生成的(23.2.3),两者的只读堆对象、指针、code cache checksum 是绑定的。换掉底层 V8 快照,上层 Node 快照里的引用就失去意义。这与 23.1.7 的 v8Flags 延后应用、23.2.3 的 flags hash 对齐是同一个不变量:快照与其消费环境必须逐字节配套。
node_natives_code_cache.cc:26-32 依据是否嵌入快照选择 code cache flavor;electron_natives_codecache_main.cc:174 里构建工具同样调 GetEmbeddedSnapshotData() 来决定生成哪一套缓存。也就是说,这个选择不只影响启动,还影响构建期产出哪份 code cache。
23.2.7 一个 fuse 的性能反噬:安全换来的启动回退
fuses.md:107-129 的 loadBrowserProcessSpecificV8Snapshot 条目,前半段讲安全收益(主进程与渲染器用不同 V8 快照,避免渲染器拿到带 nodeIntegration 的快照),最后一段是与本章直接相关的:
When the main process runs on a custom V8 snapshot -- this fuse, or a
v8_context_snapshot.binreplaced with one generated byelectron-mksnapshot-- Electron bootstraps the main process's Node.js environment from source instead of from its embedded Node.js startup snapshot, so that the objects in the custom snapshot are available to the main process. This costs part of the main-process startup time the embedded snapshot otherwise saves.
把 23.2.1–23.2.6 串起来,这条文档陈述就能从源码推出来:
开启 loadBrowserProcessSpecificV8Snapshot fuse
→ GetBrowserV8SnapshotFilename() 返回 browser_v8_context_snapshot.bin
→ LoadedV8SnapshotIsBuiltIn() 判定"不是构建自带那份"
→ NodeSnapshotForThisProcess() 返回 nullptr
→ JavascriptEnvironment 不传空 context(electron_browser_main_parts.cc:319-324 的分支不进)
→ node::CreateEnvironment 从源码 bootstrap
→ 阶段 5 变慢
这是本章第一个"优化之间会互相抵消"的实例。第 20 章讲 fuses 时把 fuse 当作安全开关,这里看到它同时是一个性能开关;第 22 章讲 embeddedAsarIntegrityValidation 时看到它管住了 asar 和快照两处校验,这里看到另一个 fuse 管住了快照选择并连带放弃 Node 快照。做安全加固时如果把这些 fuse 全部打开,冷启动会付出叠加代价。文档用的是 "costs part of",没有给数字——本章沿用这个克制。
顺带说一句:fuses.md:113-114 那句 "V8 snapshots can be useful to improve app startup performance ... avoid the cost of initializing the heap" 讲的是 fuse 的动机,但 fuse 本身的效果恰恰是让主进程不吃 Node 快照。把这两句连起来读会觉得矛盾,其实前者解释为什么要单独给主进程一份快照,后者解释代价。文档没有把因果关系写透,源码补全了。
23.2.8 code cache flavor:一个构建期分叉的四份产物
BUILD.gn:922-974 定义了 electron_natives_codecache 与 electron_natives_codecache_snapshot。:923-926 的注释说明它们"Built in v8_snapshot_toolchain (like node_mksnapshot)";:951-957 解释了为什么需要单独一个 variant:
# The browser process boots from the embedded Node startup snapshot, whose
# read-only heap (and thus the code-cache read-only checksum) is owned
# uniquely by the SnapshotCreator-produced blob -- matching no standalone
# snapshot file. This variant links the real node_snapshot so it builds the
# browser bundles' cache against that exact snapshot's isolate ...
V8 的 code cache 里带一份只读堆的 checksum,用 A 快照生成的 cache 在 B 快照上会被拒绝。浏览器进程用的是 node_mksnapshot 产出的那份独有 blob,所以它必须有一套专门对着这份 blob 的 isolate 生成的 code cache。:1003 的 node_builtins = !node_use_node_snapshot、:1016-1087 的 browser flavor 条件分支、:1078 的 snapshot_blob.bin 都在这条链上。
BUILD.gn:977-1010 的 _js2c_cc_flavors 列出四个 flavor(browser / renderer / utility / worker / sandbox,注释记为约 6.5 MB 每份)。也就是说"构建期 code cache"不是一个文件,而是一组按进程类型与快照组合生成的产物,运行期由 node_natives_code_cache.cc:42-48 的 CurrentProcessJs2cCacheFlavor() 选出一份。下一节讲这个选择如何在运行期兑现。
23.2.9 快照省了什么、没省什么
收束这一节,避免把 V8 快照当成万能药:
| 省掉 | 没省掉 |
|---|---|
| V8 内置对象堆的初始化 | 可执行文件的加载与动态链接 |
| Node bootstrap 的源码解析与编译(仅浏览器/utility 进程) | lib/browser/init.ts 及其预加载的四个模块 |
| 内部 bundle 的源码编译(配合 code cache) | 用户 package.json 解析之外的应用 require() 图 |
| 渲染器 preload 的首次编译(配合 23.4 的缓存) | 窗口创建、页面加载、GPU 进程启动 |
ValidateV8Snapshot 的整 blob SHA256(开 fuse 时) |
最右边一列里,用户自己的 require() 图是官方文档八条建议的主战场(23.5),窗口与页面加载是 23.4 与 23.13 的主题。快照解决的是"Electron 自己的固定成本",解决不了应用自己的固定成本——这个区分是理解本章后续所有内容的前提。
all.gn:83-85 的 v8_enable_private_mapping_fork_optimization = true 加速的是 fork/execve 后的只读映射复用,属子进程创建优化,不是主进程冷启动;all.gn:33-34 则因 "this breaks mksnapshot" 关掉了 v8_enable_snapshot_native_code_counters。这类一行配置,往往是排查「本地构建与官方二进制启动表现不同」的入口。
23.3 构建期 code cache 与 bundle:把编译也搬走
23.3.1 先纠正一个流传很广的说法:这里没有 webpack 分块
bundle.mjs 是本树打包内部 TS 模块的地方。检索 lib/**/*webpack* 零命中,build/bundle 里 webpack 只出现在 bundle.mjs:125 的一句类比注释里("like webpack's ProvidePlugin")。实际的 bundler 在 bundle.mjs:177 是 await rolldown(...),且 :209-224 明确写死:
bundle.mjs:209-224
codeSplitting: false,
format: 'cjs',
:227-234 还断言输出只允许一个 chunk。也就是说:Electron 内部 bundle 不做代码分割,每个 flavor 就是一个 CJS 文件,被编成二进制里的 electron_natives 数组(第 8 章讲七个 bundle 时展开过)。如果按"webpack chunk 懒加载"去理解 Electron 的启动,会推导出完全错误的优化手段。
:198-207 另有一条注释值得记下来:--mode=production 只决定 minify,"testing builds run the same module graph as releases"。所以本地调试构建与发布构建在模块图上是一致的,测启动路径时不会因构建模式不同而失真——但 minify 本身会影响解析时间,跨模式比绝对毫秒数仍然没有意义。
BUILD.gn:36-46 的 electron_generate_js2c_code_cache = host_os == target_os 是这一整套机制的开关,注释写着 "Emit a build-time V8 code cache ... bundles compile from source"。注意它只比较 host_os 与 target_os,不比较 CPU——与 23.2.2 里 Node 补丁改用 node_snapshot_toolchain_runs_target_code 形成对照。这两条判据作用在不同层:前者是 Electron 自己 bundle 的 code cache,后者是 Node 内建模块的快照。
23.3.2 真正的懒加载机制:nodeExternalsPlugin
bundle.mjs:146-175 是本节最该逐字读的一段:
// In a Node.js environment the bundle is called with Node's internal
// `require`, which serves both public built-ins and lib/internal/* modules.
// A plain external `import` would be hoisted to a require() at the very top of
// the bundle; routing it through a one-line CommonJS shim instead keeps the
// require() lazy, so a built-in is only loaded once the (lazily evaluated)
// module importing it actually runs, as it was with webpack.
const nodeShimPrefix = '\0electron-node-external:';
:154-175 的插件判断 kind === 'require-call':只有字面量 require('fs') 这种形式才标为 external;其余(例如 import 进来的内置模块)生成一行 module.exports = require(...) 的 shim。差别在于 ESM import 会被提升到 bundle 顶部执行,而 shim 里的 require 只在模块第一次被求值时运行。
这解释了一个看起来矛盾的现象:bundle 是单 chunk,但内部模块仍可懒加载。懒的不是 chunk,是 Node 内置模块的加载时机。第 8 章讲七个 bundle 与两个注册表时,lib/browser/init.ts:15-31 那个在 uncaughtException 回调里才 require('electron') 的写法,正是这套思路在应用侧的同构——注释给的理由也一样直接:不能在文件顶部 import,因为这个 init 文件本身负责建立 require hook。
bundle.mjs:124-127 的 inject 是另一处细节:
// Free variables that are rewritten to imports of an internal module, like
// webpack's ProvidePlugin. Every bundle captures the original Promise so that
// user land replacing the global does not affect Electron.
const inject = { Promise: ['@electron/internal/common/primordials', 'Promise'] };
把 Promise 重写成内部 primordials 的导入,是为了防止用户代码改全局 Promise 影响 Electron 内部。这是安全性改写,但它也意味着 bundle 里的每个 Promise 都多一层模块间接,属于启动期固定成本的一部分。
23.3.3 运行期兑现缓存:CompileBundle 与 flavor 选择
node_util.cc:25-50 是把构建期 code cache 用起来的地方:
v8::MaybeLocal<v8::Function> CompileBundle(
v8::Isolate* isolate, v8::Local<v8::Context> context, ...) {
static base::NoDestructor<
base::ThreadLocalOwnedPointer<node::builtins::BuiltinLoader>>
builtin_loader;
if (!builtin_loader->Get()) {
auto loader = std::make_unique<node::builtins::BuiltinLoader>();
// Feed the build-time js2c code cache so the framework bundles are
// consumed instead of compiled from source. Must run before the first
// LookupAndCompileFunction; empty on builds without a generated cache.
const bool has_node_env = node::Environment::GetCurrent(context) != nullptr;
const auto& cache =
GetNativesCodeCache(CurrentProcessJs2cCacheFlavor(has_node_env));
if (!cache.empty())
loader->RefreshCodeCache(cache);
builtin_loader->Set(std::move(loader));
}
v8::MaybeLocal<v8::Function> compiled =
builtin_loader->Get()->LookupAndCompileFunction(
context, id, parameters, node::Realm::GetCurrent(context));
三个要点:
- "Must run before the first LookupAndCompileFunction" ——
RefreshCodeCache必须在第一次编译之前灌进去,晚了就没用。这与 23.1.7 的v8Flags延后、23.2.3 的 flags hash 是同一类顺序约束; CurrentProcessJs2cCacheFlavor(has_node_env)用「当前 context 有没有 Node Environment」参与选 flavor——同一个进程里可能出现两种 context(例如主进程的普通 context 与某些内部 realm),所以要按 context 判,不能只按进程类型判;static+ThreadLocalOwnedPointer:每个线程一份 loader,避免跨 isolate 复用。
node_bindings.cc:1044 是调用 CompileBundle 加载 init bundle 的位置;node_natives_code_cache.cc:42-48 实现 flavor 到缓存字节的映射。回看 23.2.8 那个"四份 flavor"的分叉,运行期就落在这一行 CurrentProcessJs2cCacheFlavor() 上。
bundle.mjs:274-280 还有一条构建侧的稳定性措施:内容未变则不重写输出文件,让 ninja restat 跳过下游 electron_natives.cc 的重编译。这条与性能无关,但解释了为什么改动一个 TS 文件有时会触发长时间的 C++ 重编——只要 bundle 字节变了,restat 就失效。
23.3.4 common/init.ts:一笔必须付的固定开销
lib/common/init.ts 123 行,每个进程都会跑。与启动开销相关的部分:
:8-21wrapWithActivateUvLoop()—— 注释解释 Node 与 Chromium 双事件循环下必须主动process.activateUvLoop(),否则 Node 回调不会唤醒 Chromium 消息泵。这是第 6 章那条链路在 JS 侧的兑现,每个被包装的定时器调用都多一次激活;:37-61包装process.nextTick、setImmediate、setTimeout、setInterval,但:56-61只在 browser / utility 进程替换全局,注释写明 "We skip renderer with nodeIntegration here"。渲染器里如果开了nodeIntegration,它的定时器不是这套包装;:63-75Windows 下伪造 stdinReadable,且require('stream')是懒的;:77-99makeElectronModule()造一个假的electron模块缓存,并按process.type注册electron/main/electron/renderer/electron/utility别名;:101-122覆写Module._resolveFilename把别名映射到'electron'。
:56-61 的分叉意味着渲染器里用 setTimeout 与主进程走的是不同实现路径(第 6 章主要看主进程)。
23.3.5 --profile-electron-init:为了测量而故意变慢
targets.mjs:19-30 的 wrapInitWithProfilingTimeout 注释:
Defer running the bundle by a tick when
--profile-electron-initis passed.
bundle.mjs:250-258 实现这个推迟,目的是给 profiler 留出挂载时间——否则 init bundle 在 profiler 附上前就跑完了,测量不到。targets.mjs:30 说明该标志只对 renderer target 开启。
触发它的开关在 electron_browser_client.cc:698-701:
auto env = base::Environment::Create();
if (env->HasVar("ELECTRON_PROFILE_INIT_SCRIPTS")) {
command_line->AppendSwitch("profile-electron-init");
}
这里有一个必须讲清楚的方法论陷阱:测量手段本身改变了被测对象。加了 ELECTRON_PROFILE_INIT_SCRIPTS=1 之后,渲染器 init 被推迟一个 tick,窗口首帧时间会与不加时不同。这个环境变量是用来抓 init 阶段 CPU profile 的,不是用来量"真实冷启动"的。23.11 会把所有可用的测量开关按"是否改变被测路径"分一次类。
23.4 RendererStartupData 预推:把同步 IPC 从关键路径上摘掉
23.4.1 被替换掉的那条同步 IPC
本节讲的是本树相对旧版 Electron 变化最大的一处启动优化。electron_api_web_contents.cc:2812-2831 的注释直接点名了被替换的方案:
mojom::RendererStartupDataPtr data;
{
// We're on the UI thread. The asar is mmap'd and offset-indexed so warm
// reads are fast; cold reads block briefly. Crucially the renderer is NOT
// parked waiting on us here -- we haven't sent CommitNavigation yet -- so
// unlike the old sync IPC handler this can't amplify under contention.
ScopedAllowBlockingForElectron allow_blocking;
data = renderer_startup_data::BuildForFrame(rfh, url, origin);
}
旧方案里渲染器在 DidCreateScriptContext 发同步 IPC 回浏览器等数据,有三层问题:渲染器阻塞、UI 线程同步读 asar、多个渲染器冷启动时请求在 UI 线程排队放大。
新方案把数据从"渲染器来要"改成"浏览器主动推":在 ReadyToCommitNavigation(:2834-2839 调用 MaybeSendRendererStartupData())时就把整包数据发过去,那时 CommitNavigation 还没发出,渲染器还没开始建 context,读 asar 的时间不落在任何等待链上。
23.4.2 数据包里到底装了什么
定义在 api.mojom:8-33:
// A preload script and its contents, pushed to the renderer ahead of the
// document that needs it.
struct PreloadScriptData {
...
// UTF-8 contents. array<uint8> rather than BigBuffer so RendererStartupData
// can be flat-serialized into an opaque blob for the CreateNewWindowReply
// path.
array<uint8> contents;
...
// V8 code cache, produced by the first renderer to compile this preload and
// persisted under userData/Code Cache/electron-preload/. Only shipped when
// its recorded source hash matches |contents|.
array<uint8>? code_cache;
};
// Everything a sandboxed renderer needs to bootstrap a preload environment.
struct RendererStartupData {
array<PreloadScriptData> preload_scripts;
// Browser process.env, captured fresh per push.
map<string, string> environment;
string helper_exec_path;
};
三条设计约束藏在注释里:
contents用array<uint8>而不是BigBuffer,是为了让整个RendererStartupData能被扁平序列化成一段不透明 blob(23.4.5 的 window.open 路径需要);code_cache是可选的,且只在源文件 SHA256 匹配时才附上;environment每次推送现取,不缓存。
结构体上方还有一条注释(api.mojom:25-27):process.arch / platform / version / versions 故意不放进 RendererStartupData,由渲染器侧从 node::per_process::metadata 自己填。这是同一份数据包上的又一处剪枝——能在本进程算出的常量,不值得跨进程序列化。
api.mojom:47-53 的注释写明了顺序保证:SetStartupData() 先于 CommitNavigation 到达;interface ElectronFrame { SetStartupData(RendererStartupData data); }。
23.4.3 BuildForFrame:读盘、哈希、查缓存
renderer_startup_data.cc:92-99 共 195 行,是这份数据的组装处。
ReadPreloadScript()(:80-110)里有一段值得注意的剪枝:
renderer_startup_data.cc:92-99
// A frame with Node.js integration loads its preloads through Node's own
// module loader and only needs to be told which files; reading them (and
// consulting the code cache) here would be wasted work.
if (!read_contents)
return ps;
std::string contents;
if (!asar::ReadFileToString(path, &contents)) {
ps->error = "ENOENT: ...";
...
}
ps->contents.assign(contents.begin(), contents.end());
if (served) {
const preload_code_cache::SourceHash hash =
crypto::hash::Sha256(ps->contents);
std::vector<uint8_t> cache = preload_code_cache::Get(scope, id, hash);
if (!cache.empty())
ps->code_cache = std::move(cache);
served->emplace_back(id, hash);
也就是说 nodeIntegration 渲染器不读 preload 内容,只拿路径列表——它自己有 Node 模块加载器,浏览器进程替它读一遍纯属浪费。这是第 12 章"两条 preload 加载路径"在性能侧的体现。
CaptureBrowserEnvironment()(:35-52)每次推送调 uv_os_environ() 取当前环境,注释说明这样能保证与"每次导航同一时机"的语义一致;GetHelperExecPath()(:54-58)取 content::CHILD_PROCESS_EXE。这两项只在沙箱渲染器里附上(:141-146):
renderer_startup_data.cc:143-145
// A Node.js renderer has the real process.env and computes helperExecPath
// itself; only the sandboxed process shim needs these.
if (sandboxed) {
data->environment = CaptureBrowserEnvironment();
data->helper_exec_path = GetHelperExecPath().AsUTF8Unsafe();
}
BuildForFrame()(:160-192)把 session 级注册的 preload 和 webPreferences.preload 合并,后者追加在最后(:172-184),并调 RecordServedPreloads(:186-190)记下本次发出的 (id, hash) 元组。preload_code_cache.h:65 的注释说明这些记录是后续 SetPreloadCodeCache 写入时的信任锚:只有浏览器确实发过这份源码的渲染器,才有资格回传它的 code cache。这防的是渲染器被攻破后往缓存里塞任意字节码。
23.4.4 通道顺序:为什么推过去就一定先到
electron_api_web_contents.cc:2822-2831 的注释解释了这层保证:
// GetRemoteAssociatedInterfaces() routes over the same channel as
// content.mojom.Frame (the navigation channel), so a push from
// ReadyToCommitNavigation is ordered before the CommitNavigation ...
// is ordered before anything else on the frame. The renderer's
// ElectronApiServiceImpl -- created in RenderFrameCreated, before any
// navigation -- will have cached it by the time DidCreateScriptContext fires.
mojo::AssociatedRemote<mojom::ElectronFrame> frame_startup;
rfh->GetRemoteAssociatedInterfaces()->GetInterface(&frame_startup);
frame_startup->SetStartupData(std::move(data));
关键是 AssociatedRemote:它走的是与 content.mojom.Frame 同一条 mojo 通道,因此消息顺序由通道保证,不需要额外的 barrier 或 ack。如果换成独立的 Remote(独立管道),推送与 CommitNavigation 之间就没有顺序保证,渲染器可能在数据到达前就建了 context。这是一个"用通道语义替代显式同步"的典型设计,也解释了为什么 api.mojom:47-53 敢把顺序写成注释而不是代码。
MaybeSendRendererStartupData()(:2764-2803)在推之前还有一组过滤条件;electron_browser_client.cc:856-874 的 GetServiceWorkerStartupData() 里另有一句同类剪枝注释:"Skip the asar reads + serialization otherwise -- this runs on every service worker start"。服务 worker 每次启动都会走这条路径,所以不必要时连读盘加序列化都要省掉。
23.4.5 window.open() 的同步 about:blank:一条旁路
上面那条"推送先于 CommitNavigation"的保证,有一个场景覆盖不到:window.open() 不传 URL 时,新窗口的 RenderFrame、同步的 about:blank 文档、以及 embedder preload 全在渲染器自己的调用栈里创建,浏览器进程根本没有一次导航可以用来夹带推送。
feat_carry_embedder_startup_data_in_createnewwindowreply.patch:9-26 把问题写得很清楚:
Add an opaque BigBuffer field to CreateNewWindowReply, populated via a
new ContentBrowserClient::GetExtraCreateNewWindowReplyData() hook (called
unconditionally; the embedder decides whether to return data -- Electron
returns it only for windows that stay on about:blank ...), and
consumed via a new ContentRendererClient::SetPendingCreateNewWindowStartupData()
hook called before the new RenderFrame is created ...
补丁的四段::28-44 在 render_frame_host_impl.cc 填 reply->electron_startup_data;:46-70 在 frame.mojom 加 mojo_base.mojom.BigBuffer? electron_startup_data;;:73-120 给 ContentBrowserClient 加默认返回 std::nullopt 的虚函数;:121-169 给 ContentRendererClient 加 SetPendingCreateNewWindowStartupData() 并在 render_frame_impl.cc 里、创建 RenderFrame 之前消费。
Electron 侧的填充在 electron_browser_client.cc:822-874:
// A window.open() popup's synchronous about:blank fires
// DidCreateScriptContext -- and runs the preload -- before any async push can
// land. ...
// Only the about:blank document needs this. A popup that navigates
// (window.open(url)) does not run the preload on its initial document ...
// building the data here for it would be pure waste.
if (!target_url.is_empty() && !target_url.IsAboutBlank())
return std::nullopt;
...
mojom::RendererStartupDataPtr data;
{
ScopedAllowBlockingForElectron allow_blocking;
data = renderer_startup_data::BuildForFrame(
new_window_main_frame, GURL(url::kAboutBlankURL),
new_window_main_frame->GetLastCommittedOrigin());
}
// Opaque blob -- Chromium can't depend on Electron's mojom types.
return mojo_base::BigBuffer(mojom::RendererStartupData::Serialize(&data));
两处剪枝值得单独记:只有停留在 about:blank 的弹窗才需要这份数据(带 URL 的弹窗初始文档不跑 preload);以及序列化成不透明 BigBuffer 是因为 Chromium 不能依赖 Electron 自己的 mojom 类型。这正是 23.4.2 里 contents 必须用 array<uint8> 的原因——整个结构要能被 Serialize() 成一段字节。
渲染器侧的交接:renderer_client_base.cc:349-359 反序列化并调 SetPendingNewWindowStartupData;electron_api_service_impl.cc:130-158 用 std::exchange 取出 pending 数据再 SetStartupData()。源码注释强调 "Same call stack, no reentrancy"——这份数据不经过任何异步边界,直接挂在同一个调用栈上,等 DidCreateScriptContext 来取。
23.4.6 消费侧:code cache 如何被安全地用上
electron_renderer_client.cc:120-203 的 DidCreateScriptContext 是终点。两个细节:
// Before we load the node environment, let's tell blink to hold off on
// loading the body of this frame. We will undefer the load once the preload
// script has finished. This allows our preload script to run async (E.g.
// with ESM) without the preload being in a race
render_frame->GetWebFrame()->GetDocumentLoader()->SetDefersLoading(
blink::LoaderFreezeMode::kStrict);
以及 :182-196 从 ElectronApiServiceImpl::startup_data() 里取出 preload 路径写进 process.preloadPaths,注释点明 "so renderer init does not have to ask for them with a synchronous IPC"——与 23.4.1 呼应。lib/renderer/init.ts:145 随后用 getHiddenValue(process, 'preloadPaths') 读出来,按 .mjs 分成 CJS / ESM 两组分别加载(:146-177)。
preload_utils.cc:92-112 的 LookupPreloadScript() 从 mojo 缓存的 startup data 里取 contents 与 cache,注释强调 "without entering V8"——原生缓冲区直接可用,不需要先转成 V8 字符串。:124-161 的 CreatePreloadScript() 有一处很巧的防御:
// Contents/cache stay in native buffers; only the single NewFromUtf8 copy
// for the compile touches V8.
...
// V8 validates a code cache against the source but not against the
// parameter names. Name the parameters in a trailing comment so a persisted
// cache made for a different parameter list ... is rejected and rebuilt ...
body = v8::String::Concat(isolate, body,
gin::StringToV8(isolate, "\n//# electronPreloadParameters=" ...));
...
std::unique_ptr<v8::ScriptCompiler::CachedData> cached_data;
if (ps->code_cache) {
base::span<const uint8_t> cache = *ps->code_cache;
cached_data = std::make_unique<v8::ScriptCompiler::CachedData>(
cache.data(), base::checked_cast<int>(cache.size()),
v8::ScriptCompiler::CachedData::BufferNotOwned);
}
V8 的 code cache 校验只比对源码,不比对 wrapper 的参数名。preload 的 wrapper 参数是固定的五个(preload_environment.cc:266:require / process / exports / module / global),但如果 Electron 升级改了这个列表,旧缓存仍会被 V8 接受,然后在错误的参数绑定下执行。解决办法是把参数列表写进源码末尾的注释里——源码变了,V8 的源码比对自然拒绝旧缓存。这是一个用"改源码"而不是"加版本号字段"来复用既有校验机制的做法。
BufferNotOwned 也值得留意:缓存字节仍归 mojo 消息所有,CachedData 只是借用,避免一次拷贝。
23.4.7 沙箱 realm 与 nodeIntegration 的两条分支
不是所有 preload 都走上面那条路。preload_realm_context.cc:169-210 处理 service worker / preload realm(第 16 章讲过的隔离世界)::178-182 反序列化 RendererStartupData 存进 ServiceWorkerData;:185-192 构造 process 并设 contextIsolated 为 true;:194-197 的注释 "Create ipcRenderer up front so that messages from the browser have somewhere to go before a preload script asks for it" 说明 ipcRenderer 必须提前建好;:272-273 用 blink::DOMWrapperWorld::Create(isolate, WorldType::kShadowRealm) 创建隔离世界。
preload_environment.cc:248-293 的 RunPreloadScripts() 遍历 data->preload_scripts(:269),跳过空内容(:277-278),逐个 CreatePreloadScript + Call。
而 nodeIntegration 渲染器这侧,renderer_startup_data.h:44-46 的注释已经把结论写死了:
For a frame without the sandbox (Node.js integration) only the preload paths are filled in: that renderer loads the files itself.
所以本章标题里的"把同步 IPC 从关键路径上摘掉",要加一个限定:对沙箱渲染器与 preload realm 成立;nodeIntegration 渲染器本来就不需要浏览器代读,但也因此拿不到这份持久化的 preload code cache。开启 nodeIntegration 除了第 15 章讲的安全边界变化,在启动路径上还意味着放弃 23.4 整套预推与缓存机制中的编译缓存部分。
23.4.8 代价边界
把这一节的取舍列清楚,避免把"预推"理解成纯粹的免费午餐:
| 收益 | 代价 / 边界 |
|---|---|
| 渲染器不再同步等待 | 浏览器 UI 线程仍要 ScopedAllowBlockingForElectron 同步读 asar(冷读会阻塞,只是不落在渲染器等待链上) |
| preload 首次编译可跳过 | 每次导航都要 CaptureBrowserEnvironment() + SHA256 + 缓存查询 |
| 跨进程顺序由 mojo 通道保证 | 依赖 AssociatedRemote 与 content.mojom.Frame 共通道,换成独立管道即失效 |
| window.open 同步 about:blank 有数据 | 为此改了 Chromium 的 frame.mojom 与两个 client 接口(一个补丁,169 行) |
| 缓存由渲染器回传、浏览器落盘 | 需要 RecordServedPreloads 做信任锚,防止被攻破的渲染器污染缓存 |
| 弹窗带 URL 时不生成数据 | 剪枝条件 !target_url.is_empty() && !IsAboutBlank(),条件写错会退化成每次都白做 |
api.mojom:19-22 指明缓存落在 userData/Code Cache/electron-preload/,与 Electron 版本、preload 源码、wrapper 参数列表绑定;升级 Electron 或改 preload 后首次启动会重新编译,这是「升级后第一次启动变慢」的一个具体来源。
23.5 performance.md 八条建议,逐条对照源码
23.5.1 这份文档的定位
performance.md 共 448 行,是官方唯一一份集中谈性能的教程::26-31 声明清单并非穷尽、性能主要由应用开发者负责,:33-53 推荐 Chrome DevTools 与 Chrome Tracing,:60-72 列出八条目录。按「是否有本树源码支撑」分类比逐条复述更有用:
把八条按"是否有本树源码支撑"分类,会比逐条复述更有用:
| # | 标题 | 行号 | 源码可核对程度 |
|---|---|---|---|
| 1 | Carelessly including modules | :74-138 | 经验性;require() 代价可在 23.3 找到机制解释 |
| 2 | Loading and running code too soon | :140-234 | 经验性;与 23.1.9 的阶段 9/10 对应 |
| 3 | Blocking the main process | :236-275 | 部分:ipc.md:356 与同步 IPC 实现 |
| 4 | Blocking the renderer process | :277-311 | 经验性(Web Platform 建议) |
| 5 | Unnecessary polyfills | :313-349 | 可核对:process.versions.chrome 与 DEPS 版本 |
| 6 | Unnecessary or blocking network requests | :351-398 | 经验性 |
| 7 | Bundle your code | :400-422 | 与 23.3.1 的单 chunk 内部 bundle 不是一回事 |
| 8 | Menu.setApplicationMenu(null) | :424-434 | 全篇唯一明确讲启动性能的一条 |
下面按组展开,重点放在"文档说法与源码事实之间的缝隙"。
23.5.2 第 1、2、7 条:require() 的代价到底从哪来
第 1 条给了一个具体例子(:82-109):一个 isOnline() 模块在 require() 时读进十万行 JSON,在慢机器上要花"whole seconds";:99-104 强调服务端启动时间不重要,但客户端每次冷启动都要付。诊断命令在 :119-130:
performance.md:124
node --cpu-prof --heap-prof -e "require('request')"
:136-138 给出对比数字:request 接近 0.5 秒,node-fetch 小于 50 毫秒。这是整份文档里唯一一组具体数值,且明确标注是测量示例而非基准。
第 2 条(:140-234)的 parser.js 前后对比更有教学价值:改造前在模块顶层 new Parser() 并同步 readdirSync(:176-194);改造后把 require('foo-parser') 移进 getParsedFiles() 内部、readdirSync 换成 fs.promises.readdir(:200-231)。:155 的注释指出模块加载"especially on Windows"昂贵,这与第 22 章讲 asar 时 application-distribution.md:55-60 说的"asar 在 Windows 上能改善读文件性能"是同一现象的两面——文件数量与 stat 次数在 Windows 上比在 POSIX 上贵得多。
第 7 条(:400-422)说 "calling require() is an expensive operation",建议把代码打成单文件,让开销只付一次(:407-412),并举例 Webpack / Parcel / rollup.js(:421-422)。这里必须补一条本树的实情:这条建议说的是应用代码,不是 Electron 自己的内部 bundle。23.3.1 已经说明 Electron 内部 bundle 用 rolldown 打成单 chunk 且关闭 code splitting,但那是 C++ 侧 node::builtins::BuiltinLoader 从内存数组编译的,不经过 Node 的文件系统模块解析,两者的"require 开销"不是同一个东西。把第 7 条套到 Electron 内部机制上会得出错误结论。
从源码看,应用侧一次 require() 的固定成本至少有四段:路径解析(lib/common/init.ts:101-122 覆写过 Module._resolveFilename)、asar 路径判定与 header 查找(第 22 章 22.3 的 DirectoryCache)、文件读取、V8 编译。第 7 条"打成单文件"消掉的是前两段的重复次数;构建期 code cache 消掉的是最后一段,但只对 Electron 内部 bundle 生效,应用的 bundle 没有这份缓存——除非应用自己用 v8.compileFunction 或 vm.Script 的 cachedData 机制。这是 performance.md 没有明说、但对打包器选型影响很大的一条。
23.5.3 第 3、4 条:两个"主线程"不是一回事
第 3 条(:236-275)说主进程是"控制塔",绝不能阻塞 UI 线程;:264-266 给出三条替代方案(worker threads / 新建 BrowserWindow / 独立进程),:268-270 要求避免同步 IPC 与 @electron/remote。ipc.md:356 对同步 IPC 的说明是 "avoiding this API for performance reasons. Its synchronous nature means that it'll block..."。
这里有一条本树提供的、文档没写的强证据:23.4.1 那段注释讲的是 Electron 自己曾经在 DidCreateScriptContext 里用同步 IPC 取 preload 数据,后来专门改架构把它摘掉,理由是"渲染器被停住等待"且"在争用下会放大"。官方文档劝应用别用同步 IPC,而 Electron 自身在 45.2.3 里已经把关键路径上的最后一次同步 IPC 换成了 mojo 预推。这比任何说教都更能说明问题。
第 4 条(:277-311)讲渲染器::283-291 用 60fps 论证,:297-298 建议 requestIdleCallback() 处理小任务、Web Workers 处理长任务。要注意第 4 条里的"主线程"是 Blink 的渲染主线程,与第 3 条的浏览器 UI 线程是两个不同进程里的两个不同线程。app.getAppMetrics() 返回的 CPU 是按进程聚合的(23.7),看不出某个线程被阻塞;要定位线程级阻塞只能用 23.9 的 trace。把两条建议混起来、然后指望 getAppMetrics() 验证效果,是常见的方法论错误。
23.5.4 第 5、6 条:可核对的版本事实与不可打包的外部请求
第 5 条(:313-349)的核心论据是"Electron 的引擎版本是确定的,不需要为旧浏览器写 polyfill",:340 给出核对手段 process.versions.chrome,:347-349 建议 TypeScript target 设成最新 ECMAScript。这条在本树里可以精确核对:DEPS:3-7 写明 Chromium 156.0.8078.80、Node v24.22.2,all.gn 里的 NODE_MODULE_VERSION 是 150(见总目录 1.1 的依赖矩阵)。第 1 章已经把这张表铺开过,这里补上它的性能意义:Blink / V8 / Node 三者版本都锁死,所以任何"兼容旧引擎"的转译与 polyfill 都是纯开销,没有收益侧。
第 6 条(:351-398)建议把不常变资源打进包、用 DevTools Network 的 Disable cache + reload 盘点大文件(:379-382)、用 Fast 3G 节流模拟(:389-393)、考虑 Service Workers(:395-398)。这条与第 17 章的网络栈直接相关:应用里一个外部字体请求会走完整的 InterceptState::RouteFor 判定、webRequest 监听者、以及可能的代理路径,而且落在窗口首屏关键路径上。asar-archives.md:186 另外提到杀毒软件扫描对读归档的性能影响,属于同一类"外部不可控延迟"。
23.5.5 第 8 条:唯一一条明确说启动的建议
:424-434 全文只有三句实质内容:
Electron will set a default menu on startup ... it will benefit startup performance. Call
Menu.setApplicationMenu(null)beforeapp.on("ready").
附带的 issue 是 #35512。这条之所以值得单独讲,是因为它把"启动时序"暴露出来了:默认菜单的构建发生在 ready 之前,属于 23.1.9 表里阶段 8–9 之间的 native 工作;在 ready 之前调用 setApplicationMenu(null) 能让这段工作被跳过,而在 ready 之后调用只是把已经建好的菜单替换掉,付过的成本收不回来。
但从源码角度要克制:command-line-switches.md:5-7 说 appendSwitch 必须在 ready 前,与这里是同一类时序约束;本树并没有给"默认菜单构建耗时 X 毫秒"的打点(23.1.8),所以无法从源码量化这条建议的收益。第 18 章讲 Menu 时展开过 buildFromTemplate 的拓扑排序与 ItemRef 快照,那些是菜单构建的实际工作量所在。正确的表述是"这是一条有时序条件的剪枝建议",而不是"这能快多少"。
23.5.6 文档没写、但源码里确实存在的三条
对照下来,performance.md 覆盖的是应用侧启发式,本树里三项最大的启动优化它一条都没提:
- V8 / Node 启动快照(23.2)——由补丁与 GN target 决定,应用只能通过 fuse 间接影响,而且影响方向可能是负的;
- 构建期 js2c code cache 与
RendererStartupData预推(23.3、23.4)——完全由 Electron 内部完成,应用能做的是别破坏它们(例如不要改v8Flags的语义、不要开nodeIntegration); backgroundThrottling与 spare renderer(23.13、23.1.2)——属于稳态资源与窗口创建延迟之间的交换,文档里只在browser-window.md:116-133的 Page Visibility 段落里以"建议暂停耗电操作"的形式出现。
23.6 ProcessMetric:一份按平台分叉的内存快照
23.6.1 结构体:字段本身就是平台差异
process_metric.h:17-57:
struct ProcessMemoryInfo {
size_t working_set_size = 0;
size_t peak_working_set_size = 0;
#if BUILDFLAG(IS_WIN)
size_t private_bytes = 0;
#endif
};
struct ProcessMetric {
int type;
base::Process process;
std::unique_ptr<base::ProcessMetrics> metrics;
std::string service_name;
std::string name;
...
ProcessMemoryInfo GetMemoryInfo() const;
#if BUILDFLAG(IS_WIN)
ProcessIntegrityLevel GetIntegrityLevel() const;
static bool IsSandboxed(ProcessIntegrityLevel integrity_level);
#elif BUILDFLAG(IS_MAC)
bool IsSandboxed() const;
#endif
};
三个立刻能读出来的事实:
type是int(Chromiumcontent::PROCESS_TYPE_*的枚举值),不是字符串。变成"Browser"/"Tab"/"Utility"是在getAppMetrics()里做的(23.7.2);privateBytes只在 Windows 存在;sandboxed/integrityLevel只在 mac / Windows 存在,Linux 一行相关代码都没有。
spec/api-subframe.spec.ts:256 有一条注释直接写明 "app.getAppMetrics() does not return sandbox information on Linux";spec/api-app.spec.ts:2121-2127 的断言也按平台分叉:非 Linux 才查 sandboxed,Windows 才查 integrityLevel。
构造函数(:62-80)在 Windows 上要复制句柄:
process_metric.cc:73-77
#if BUILDFLAG(IS_WIN)
HANDLE duplicate_handle = INVALID_HANDLE_VALUE;
::DuplicateHandle(::GetCurrentProcess(), handle, ::GetCurrentProcess(),
&duplicate_handle, 0, false, DUPLICATE_SAME_ACCESS);
this->process = base::Process(duplicate_handle);
#else
this->process = base::Process(handle);
#endif
原因是 Windows 的进程句柄有生命周期,base::Process 持有时需要自己的一份;POSIX 的 pid 可直接存。这是第 2 章讲进程句柄管理时那套跨平台差异在指标模块里的复现。
23.6.2 Windows:PROCESS_MEMORY_COUNTERS_EX
process_metric.cc:86-99:
ProcessMemoryInfo ProcessMetric::GetMemoryInfo() const {
ProcessMemoryInfo result;
PROCESS_MEMORY_COUNTERS_EX info = {};
if (::GetProcessMemoryInfo(process.Handle(),
reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&info),
sizeof(info))) {
result.working_set_size = info.WorkingSetSize;
result.peak_working_set_size = info.PeakWorkingSetSize;
result.private_bytes = info.PrivateUsage;
}
return result;
}
这里有一个容易混淆的命名:类方法叫 GetMemoryInfo(),::GetProcessMemoryInfo 是 Windows psapi API,而 JS 里的 process.getProcessMemoryInfo()(23.8.3)是第三个完全不同的东西。三者在不同的层,读的是不同的计数器。PrivateUsage 对应任务管理器里的"提交大小",与 WorkingSetSize(物理内存占用)不是同一概念。
23.6.3 macOS:task_info 与 port provider
:37-54 先解决"如何拿到别的进程的 mach port":
process_metric.cc:37-43
mach_port_t TaskForPid(pid_t pid) {
mach_port_t task = MACH_PORT_NULL;
if (auto* port_provider = content::BrowserChildProcessHost::GetPortProvider())
task = port_provider->TaskForHandle(pid);
if (task == MACH_PORT_NULL && pid == getpid())
task = mach_task_self();
return task;
}
GetPortProvider() 是 Chromium 为子进程维护的 mach port 表;查不到且 pid 等于自己时才回退 mach_task_self()。:160-169 用 task_info(MACH_TASK_BASIC_INFO) 取 resident_size 与 resident_size_max 分别填 working_set_size / peak_working_set_size。
这条实现的隐含限制是:如果 port provider 里没有目标子进程的 port,这两个字段会保持 0,且没有报错路径。第 2 章讲 macOS helper 进程与 port 注册时提到过这个表,这里是它被消费的地方之一。
23.6.4 Linux:解析 /proc/<pid>/status
:181-210:
process_metric.cc:184-191
electron::ScopedAllowBlockingForElectron allow_blocking;
std::string status;
if (!base::ReadFileToString(
base::FilePath(base::StringPrintf("/proc/%d/status", process.Pid())),
&status)) {
return result;
}
base::StringPairs pairs;
base::SplitStringIntoKeyValuePairs(status, ':', '\n', &pairs);
for (const auto& [key, value] : pairs) {
size_t* field = nullptr;
if (key == "VmRSS") field = &result.working_set_size;
else if (key == "VmHWM") field = &result.peak_working_set_size;
else continue;
std::vector<std::string_view> parts = base::SplitStringPiece(
value, " ", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
size_t kb = 0;
if (parts.size() == 2 && parts[1] == "kB" &&
base::StringToSizeT(parts[0], &kb)) {
*field = kb << 10;
}
}
三个细节:
ScopedAllowBlockingForElectron—— 这是一次真正的文件读取,发生在浏览器 UI 线程上,所以必须显式声明允许阻塞。第 22 章讲 asar 读取时见过同一个 scope;- 只认
VmRSS/VmHWM两个键,且要求值严格是"<数字> kB"两段;格式不符就静默留 0; kb << 10把 KB 转成字节。内存值的单位换算发生在getAppMetrics()里再>> 10转回 KB(23.7.2),一去一回,源码里看得清清楚楚。
也就是说,Linux 上调一次 getAppMetrics(),每个子进程都会触发一次 /proc/<pid>/status 的同步打开、读取、逐行切分。进程数多的时候这不是零成本,高频轮询尤其不划算——这条比 23.7.3 的"采样区间"更早地给出了"别把它当实时监控用"的理由。
23.6.5 sandboxed 的两种判定
Windows(:101-156)走 OpenProcessToken → GetTokenInformation(TokenIntegrityLevel) → GetSidSubAuthority,把 RID 映射成 kUntrusted / kLow / kMedium / kHigh;IsSandboxed() 判定为完整性级别低于 kMedium(:152-156)。macOS(:171-177)用 sandbox_check(pid, nullptr, 0),MAS 构建直接 return true。
Linux 没有对应实现,结构体里连条件编译分支都没有。这不是遗漏,而是 Linux 上 Chromium 的沙箱机制(user namespace / seccomp-bpf)无法用一个简单的"是/否"系统调用判定。
process-metric.md:25-26 把两者都标成 optional 且带平台标签,与源码一致。第 20 章讲 app.enableSandbox() 时讨论过沙箱粒度,这里补上:指标 API 里能否看到 sandboxed 字段,本身是平台相关的,写跨平台监控代码时必须先判字段存在性。
23.6.6 单位与口径对照
| 字段 | Windows | macOS | Linux | 最终单位 |
|---|---|---|---|---|
workingSetSize | WorkingSetSize | resident_size | VmRSS | KB |
peakWorkingSetSize | PeakWorkingSetSize | resident_size_max | VmHWM | KB |
privateBytes | PrivateUsage | 字段不存在 | 字段不存在 | KB |
sandboxed | 完整性级别 < medium | sandbox_check | 字段不存在 | boolean |
integrityLevel | RID 映射 | 字段不存在 | 字段不存在 | string |
memory-info.md:3-9 末尾写明 "all statistics are reported in Kilobytes"。三平台都叫 workingSetSize,但底层分别是 psapi 计数器、mach resident_size、VmRSS——语义相近,不等价,跨平台比较绝对值没有意义。
23.6.7 CPU 采集不在这个文件里
一个必须点明的边界:process_metric.cc:64 里没有任何 CPU 采集代码。它只负责三件事——持有 base::Process 句柄、持有 base::ProcessMetrics 实例、按平台读内存。检索 GetProcessTimes、/proc/self/stat、GetCumulativeCPUUsage、GetPlatformIndependentCPUUsage、GetIdleWakeupsPerSecond 在 shell/ 下的实现:只有 electron_api_app.cc:1496-1516 的调用点,没有本地实现。三套平台 CPU 计数在 Chromium 的 base/process/process_metrics_*.cc 里,不在本仓库(Electron 只 include base/process/process_metrics.h,见 process_metric.h:11-13)。GetProcessTimes 这个词在整个仓库零命中。
这对应本章边界④:Electron 的 ProcessMetric 是 Chromium 原语之上薄薄的一层包装。它的价值在于把 "进程列表 + 每进程内存 + 平台沙箱信息" 拼成一个 JS 字典,而不在于实现任何测量算法。下一节讲这个拼装过程,以及它带来的那个最容易误读的语义。
23.7 getAppMetrics():一次调用同时是读数、也是重置
23.7.1 表从哪来:app_metrics_ 的生命周期
electron_api_app.h:325-328:
// pid -> electron::ProcessMetric
base::flat_map<content::ChildProcessId,
std::unique_ptr<electron::ProcessMetric>>
app_metrics_;
填充有三处,全部在 electron_api_app.cc:894-901:
:566-577构造App时把浏览器进程自己塞进去,用CreateCurrentProcessMetrics();:894-911ChildProcessLaunched()在子进程启动时插入:
electron_api_app.cc:894-901
void App::ChildProcessLaunched(int process_type,
content::ChildProcessId pid,
base::ProcessHandle handle,
const std::string& service_name,
const std::string& name) {
#if BUILDFLAG(IS_MAC)
auto metrics = base::ProcessMetrics::CreateProcessMetrics(
handle, content::BrowserChildProcessHost::GetPortProvider());
#else
auto metrics = base::ProcessMetrics::CreateProcessMetrics(handle);
#endif
app_metrics_[pid] = std::make_unique<electron::ProcessMetric>(
process_type, handle, std::move(metrics), service_name, name);
}
void App::ChildProcessDisconnected(content::ChildProcessId pid) {
app_metrics_.erase(pid);
}
:831-837BrowserChildProcessLaunchedAndConnected()把ChildProcessData转成上面那条调用,其中data.metrics_name→serviceName、data.name→name。
macOS 分支多传一个 port provider,正是 23.6.3 里 TaskForPid() 依赖的那张表——指标采集与 CPU 计数在 mac 上共用一份 mach port 注册信息。
spec/api-utility-process.spec.ts:313-340 把这条链验证得很具体:utilityProcess.fork() 出来的进程在 getAppMetrics() 里 type 是 Utility、serviceName 是 'node.mojom.NodeService'、name 默认是 'Node Utility Process';传了自定义 serviceName 后 name 变成那个值。spec/api-app.spec.ts:2107-2114 则断言 Utility / GPU 类型必有 serviceName、Utility 必有 name。utilityProcess 会真实地增加 getAppMetrics() 的行数,这是第 16 章讲进程模型时没从指标角度提过的。
erase 只在断开时发生,所以这张表是"当前活着的进程",不是历史记录。想看趋势必须自己按 pid 存时间序列。
23.7.2 拼装:从 C++ 结构到 JS 字典
electron_api_app.cc:1487-1562 是完整实现,已在前面核对过原文。几个转换点:
| 源 | 转换 | 结果字段 |
|---|---|---|
process_metric.second->type(int) | content::GetProcessTypeNameInEnglish() | type(string) |
process.Pid() | 直取 | pid |
process.CreationTime().InMillisecondsFSinceUnixEpoch() | 转毫秒 | creationTime |
GetMemoryInfo() 返回值 | >> 10 | memory.workingSetSize / peakWorkingSetSize(KB) |
Windows private_bytes | >> 10 | memory.privateBytes |
service_name / name | 非空才 Set | serviceName / name(optional) |
app.ts 只有 4 行,全文是 const { app } = process._linkedBinding('electron_browser_app'); export default app;。JS 侧没有任何映射逻辑:type 字符串不是 JS 拼的,字段裁剪不是 JS 做的,整包由 C++ 的 gin 字典直接构造。这一点与第 7 章讲 gin 绑定层时的模型一致,也与很多人以为的"Node 层包装"相反。
process-metric.md:3-31 是字段的权威清单:type 的九个取值(Browser / Tab / Utility / Zygote / Sandbox helper / GPU / Pepper Plugin / Pepper Plugin Broker / Unknown)、serviceName / name 的含义、cpu、creationTime、memory、sandboxed、integrityLevel。类型定义不是手写 .d.ts——typings/*.d.ts 里检索 ProcessMetric 零命中,公共类型由这些结构文档生成(docs/ → electron.d.ts 的链路见第 22 章 22.13)。
23.7.3 最重要的一条语义:调用即开启新区间
app.md:1545-1549 与 cpu-usage.md:11-12 都写明:percentCPUUsage、idleWakeupsPerSecond 是自上次调用以来的平均值,每次调用结束就开启一段新的测量区间。实现上这不是 Electron 自己维护的计时器,而是 base::ProcessMetrics 内部保存上次 CPU 快照:GetCumulativeCPUUsage() 取当前累计值,GetPlatformIndependentCPUUsage(*usage) 用"本次累计 − 上次累计 / 墙钟间隔"算百分比,同时把本次快照存下。
由此推出四条容易踩的结论:
- 调用频率决定读数。每 100 ms 调一次与每 5 s 调一次,得到的是不同长度窗口的平均,
percentCPUUsage不能跨不同采样频率比较; - 一次调用重置所有进程。
app.getAppMetrics()是一个循环(:1492起遍历app_metrics_),循环里对每个进程都调了一次GetCumulativeCPUUsage(),所以哪怕你只想看某一个 pid,其余进程的区间也被一起重置了; - 首次调用的基准是从进程启动算起,那时
base::ProcessMetrics还没有"上一次",读数会显著高于后续稳态值。做监控要先预热一次并丢弃; - 它不是瞬时值,也不是进程 lifetime 平均。把它画成"实时曲线"时,横轴标注的应当是采样区间而不是时刻。
cpu-usage.md:14-27 还专门说明 process.getCPUUsage() 与 app.getAppMetrics() 各自维护独立区间,原因见 23.7.5。
23.7.4 percentCPUUsage 为什么除以核数
// electron_api_app.cc:1489, 1505
int processor_count = base::SysInfo::NumberOfProcessors();
...
cpu_dict.Set("percentCPUUsage", usagePercent / processor_count);
GetPlatformIndependentCPUUsage() 返回的是"该进程占用了多少个核的等价比例",在 N 核机器上理论上限接近 N×100%。除以 processor_count 之后,字段变成"占整机 CPU 容量的百分比",单进程上限约 100%。
这带来一个常见困惑:一个把单核跑满的进程,在 8 核机器上 percentCPUUsage 只有约 12.5%,看起来"很闲"。要看它是否吃满单核,得自己乘回核数,或者改用 cumulativeCPUUsage(累计 CPU 秒数)除以墙钟时间。文档没有把这个换算写进字段说明,只写了 "percentage of CPU usage",源码补上了口径。
同一段里还有个兼容性兜底(:1497):
// Default usage percentage to 0 for compatibility
double usagePercent = 0;
if (auto usage = ...->GetCumulativeCPUUsage(); usage.has_value()) {
...
}
GetCumulativeCPUUsage() 在某些平台/进程状态下返回 std::nullopt(例如进程刚退出、句柄失效),此时 cumulativeCPUUsage 字段不会被 Set,而 percentCPUUsage 为 0。cpu-usage.md:5 把 cumulativeCPUUsage 标成 optional,正是对应这个分支。写解析代码时不能假设字段一定存在。
23.7.5 两套互相独立的区间
electron_bindings.cc:34-38 里 ElectronBindings 构造自己的 metrics_ = base::ProcessMetrics::CreateCurrentProcessMetrics(),并把它绑给 process.getCPUUsage(:43-70)。而 getAppMetrics() 里浏览器进程那一项是 App 自己构造的另一个 base::ProcessMetrics 实例(:566-577)。
两个实例,两套上次快照。 于是:
- 调
process.getCPUUsage()只重置它自己那套,不影响getAppMetrics()里 Browser 那行的区间; - 反过来,调
getAppMetrics()重置所有ProcessMetric的区间,但不影响process.getCPUUsage(); - 两者算出来的
percentCPUUsage可能在同一时刻不同,因为采样起点不同。
cpu-usage.md:24-27 说的 "each call starts a fresh measurement interval" 是分实例成立的。这是本章边界④最实际的一处体现:Electron 没有统一"当前 CPU 占用"这个概念,它只是把 Chromium 的若干个独立累加器暴露出来。
23.7.6 Windows 上恒为 0 的 idleWakeupsPerSecond
electron_api_app.cc:1507-1515
#if !BUILDFLAG(IS_WIN)
cpu_dict.Set("idleWakeupsPerSecond",
process_metric.second->metrics->GetIdleWakeupsPerSecond());
#else
// Chrome's underlying process_metrics.cc will throw a non-fatal warning
// that this method isn't implemented on Windows, so set it to 0 instead
// of calling it
cpu_dict.Set("idleWakeupsPerSecond", 0);
#endif
注释把原因写全了:Chromium 的 Windows 实现里这个方法会打一条非致命警告,Electron 索性不调,直接填 0。同样的 #if 结构在 electron_bindings.cc:275-299 的 GetCPUUsage() 里也有一份(注释更简短:"NB: This will throw NOTIMPLEMENTED() on Windows")。
所以 idleWakeupsPerSecond === 0 在 Windows 上不表示"没有空闲唤醒",只表示"未实现"。任何跨平台告警规则如果对这个字段设阈值,在 Windows 上永远不触发。这类"看起来是数据、实际是哨兵"的字段,是本章反复强调"可观测性本身要单独审"的原因。
23.7.7 测试侧把字段口径钉死了
spec/api-app.spec.ts:2083-2128 是全字段校验:
pid > 0、type非空串、creationTime > 0;cpu.percentCPUUsage/cumulativeCPUUsage/idleWakeupsPerSecond均为 Number;memory.workingSetSize > 0、peakWorkingSetSize > 0;:2116-2119Windows 才断言privateBytes;:2121-2127非 Linux 才断言sandboxed,Windows 才断言integrityLevel。
注意测试断言的是类型与存在性,不是数值大小或区间语义。也就是说"调用即重置"这条行为在 spec 里没有直接覆盖,它由文档陈述 + base::ProcessMetrics 的实现共同支撑。这属于本章证据分级里较弱的一档,写监控代码时最好自己用一段 CPU 密集循环验证一遍口径,而不是只信文档。
23.8 process.* 上的六个测量入口
23.8.1 挂载表:谁能用哪些方法
electron_bindings.cc:43-70 的 BindProcess(前面已核对原文)就是完整清单。整理成表:
| 方法 | 挂载条件 | 数据来源 |
|---|---|---|
crash / hang | 所有进程 | 测试用 |
getCreationTime | 所有进程 | base::Process::CreationTime() |
getHeapStatistics | 所有进程 | v8::Isolate::GetHeapStatistics() |
getBlinkMemoryInfo | 所有进程 | Blink 内存计数 |
getProcessMemoryInfo | 仅浏览器进程 | memory instrumentation |
getSystemMemoryInfo | 所有进程 | base::GetSystemMemoryInfo() |
getSystemVersion | 所有进程 | base::SysInfo |
getCPUUsage | 所有进程 | 绑定的 base::ProcessMetrics |
mas / windowsStore | 特定构建 | 只读标记 |
方法表上方一句注释是 "These bindings are shared between sandboxed & unsandboxed renderers"——沙箱渲染器没有 Node 环境,但仍需要这些绑定,所以 BindProcess 被设计成不依赖 Node Environment。electron_sandboxed_renderer_client.cc:38-42 与 preload_realm_context.cc:72 各自调 CreateCurrentProcessMetrics() 喂给 BindProcess。
getProcessMemoryInfo 的 IsBrowserProcess() 条件会在渲染器里留下一个"方法不存在"的空缺,而 JS 侧又把它补上了——见 23.8.3。
23.8.2 getHeapStatistics 是 Electron 新增,不是 Node 的
判定链条有四段,值得完整列出,因为这是"某个 API 到底归谁"的典型取证方法:
BindProcess显式SetMethod("getHeapStatistics", &GetHeapStatistics);- 实现(
:126-152)直接调isolate->GetHeapStatistics(&v8_heap_stats),把九个字段各>> 10转成 KB 后塞进gin_helper::Dictionary,包括totalHeapSize、usedHeapSize、heapSizeLimit、mallocedMemory、peakMallocedMemory、doesZapGarbage等; process.md:3-9明确 "Electron 的 process 对象扩展自 Node.js 的 process 对象",扩展清单(:13-38、:146-265)包含这个方法;spec/api-process.spec.ts:78-91断言九个字段,:119-142的generateSpecs同一套用例在 renderer(executeJavaScript)与 main 两处都跑。
Node 原生对应物是 v8.getHeapStatistics()(模块级),不是 process.getHeapStatistics()。Electron 把等价能力挂到 process 上,是为了让沙箱渲染器(拿不到 require('v8'))也能读堆信息。preload-sandbox.js:27-32 正是沙箱 preload 里调用 getHeapStatistics / getProcessMemoryInfo / getSystemMemoryInfo / getCPUUsage 的范例。
23.8.3 getProcessMemoryInfo 有三套实现
这是本节最绕的一处,因为同一个 JS 名字在不同进程里落到了完全不同的 C++ 路径:
主进程(electron_bindings.cc:203-221)——走 Chromium memory instrumentation,返回 Promise:
v8::Local<v8::Promise> ElectronBindings::GetProcessMemoryInfo(
v8::Isolate* isolate) {
CHECK(electron::IsBrowserProcess());
gin_helper::Promise<gin_helper::Dictionary> promise(isolate);
...
memory_instrumentation::MemoryInstrumentation::GetInstance()
->RequestGlobalDumpForPid(
base::GetCurrentProcId(), {} /* allocator_dump_names */,
base::BindOnce(&ElectronBindings::DidReceiveMemoryDump,
std::move(promise), base::GetCurrentProcId()));
DidReceiveMemoryDump(:253-266)从 GlobalMemoryDump::ProcessDump 里找目标 pid,填 residentSet(仅 Linux/Windows)、private、shared,单位 KB。因为它要向所有进程请求一次全局 dump,这是一个异步且相对昂贵的操作,与 getAppMetrics() 的同步 /proc 读取完全不同。
普通渲染器(lib/renderer/init.ts:49-51)——直接覆盖成一个 IPC:
process.getProcessMemoryInfo = () => {
return ipcRendererInternal.invoke<Electron.ProcessMemoryInfo>(IPC_MESSAGES.BROWSER_GET_PROCESS_MEMORY_INFO);
};
服务端在 rpc-server.ts:8,最终落到 electron_api_web_contents.cc:5924 的 _getProcessMemoryInfo。也就是说渲染器读的其实是浏览器进程替它做的一次 dump,跨了一次 IPC。
沙箱渲染器(preload_environment.cc:143-150、:231-234)——没有 Node 环境,由 C++ 直接造出同名函数挂到 process 上。
spec/api-process.spec.ts:43-57 断言三个字段(residentSet 在 Linux/Windows 才有、private、shared)。第 22 章讲 asar 时见过"同一 fs API 在归档内外表现一致"的设计哲学,这里是同一思路:同一个 process.getProcessMemoryInfo 在三类进程里由三套代码兑现,对 JS 表现为一个返回 Promise 的函数。
23.8.4 getSystemMemoryInfo 与 getBlinkMemoryInfo
getSystemMemoryInfo(:165-200)调 base::GetSystemMemoryInfo(&mem_info),字段按平台分叉:total / free(Windows 用 avail_phys,其他用 free)、Linux 有 available、macOS 有 fileBacked + purgeable、非 macOS 有 swapTotal + swapFree,全部用 .InKiB()。:177 的注释指向 Chromium base/process/process_metrics.h 的字段解释。
这里又是一处"同名不同义":free 在 Windows 是 avail_phys(可用物理内存,含可释放的缓存),在 POSIX 是字面 free。跨平台阈值告警同样会失真。spec/api-process.spec.ts:59-69 只断言 free / total / available 的存在性。
getBlinkMemoryInfo 提供 allocated / total(:35-41 的测试断言),是 Blink 侧的堆计数,与 getHeapStatistics 的 V8 堆是两套独立分配器。一个渲染器内存涨了,究竟涨在 V8 堆、Blink 堆、还是 native / GPU 资源,要靠这三个 API 分别核对——getAppMetrics() 的 workingSetSize 只能告诉你总量涨了。
23.8.5 getCPUUsage 与 takeHeapSnapshot
getCPUUsage(:275-299)的结构与 getAppMetrics() 里每个进程的 cpu 字典完全同构:GetCumulativeCPUUsage() → GetPlatformIndependentCPUUsage() → 除以 NumberOfProcessors() → Windows 的 idleWakeupsPerSecond 填 0。差别只有实例来源(23.7.5)。
takeHeapSnapshot(:302-310)不是只读测量,它会真的生成快照:heap_snapshot.cc:46-60 用 v8::HeapProfiler::TakeHeapSnapshot() 序列化成 JSON。同类实现还在 electron_api_v8_util.cc:73-74、electron_api_web_contents.cc:5086、electron_api_service_impl.cc:248-267,mojom 定义在 api.mojom:88。spec/api-process.spec.ts:93-116 测成功与失败两条路径。
生成堆快照会暂停 JS 执行并分配大量内存,把它放进周期性监控里是典型的自伤行为。spec/api-utility-process.spec.ts:1022 展示的是另一种用法:v8.setHeapSnapshotNearHeapLimit 配合 oom-grow.js:3 fixture,在堆接近上限时自动落一份快照,属于 23.12 要讲的诊断链。
23.8.6 三个"不是":容易张冠李戴的名字
| 名字 | 判定 | 依据 |
|---|---|---|
process.resourceUsage | Node 原生,Electron 未覆盖 | shell/、lib/、process.md、typings/ 全目录检索 resourceUsage 零命中;BindProcess 无此项;扩展清单不含它 |
process.getIOCounters() | 已被移除 | docs/breaking-changes.md:1342-1344:「Chromium has removed access to this information」;代码里零命中 |
process.getHeapStatistics() | Electron 新增 | 见 23.8.2,对应 Node 的 v8.getHeapStatistics() |
getIOCounters 是曾有后被上游移除的,照旧博客写会直接拿到 undefined;docs/breaking-changes.md:1342 是判断这类问题的第一站。
process.md:3-9 那句"扩展自 Node 的 process 对象"也提示了一个排查顺序:遇到 process.* 上不认识的方法,先看 BindProcess 挂载表,再看 lib/renderer/init.ts 的覆盖,最后才去 Node 文档找。
23.8.7 按"要回答什么问题"选 API
| 问题 | 该用 | 不该用 |
|---|---|---|
| 整个应用占多少物理内存 | getAppMetrics() 求和 | getProcessMemoryInfo()(只覆盖浏览器进程) |
| 主进程 V8 堆是否泄漏 | process.getHeapStatistics() 时间序列 | workingSetSize(含所有分配器与缓存) |
| 渲染器 Blink 对象涨在哪 | getBlinkMemoryInfo() + 堆快照 | getAppMetrics()(按进程聚合) |
| 私有/共享内存拆分 | process.getProcessMemoryInfo() | memory.privateBytes(仅 Windows 且含义不同) |
| 系统还剩多少内存 | getSystemMemoryInfo() | 任何进程级指标 |
| 哪个函数占 CPU | contentTracing / --cpu-prof | percentCPUUsage(按进程) |
这张表把 23.6–23.8 收成了一句:Electron 提供的都是"进程级、快照式、平台有条件"的指标,没有"应用级、连续、跨平台统一"的指标。想要后者必须自己按固定间隔采集、按 pid 关联、按平台归一——这正是 23.16 要给出的方法论骨架。
23.9 contentTracing:唯一的进程级时间线
23.9.1 四个方法,全在 C++ 侧
content-tracing.ts:1 全文只有一行 export default process._linkedBinding('electron_browser_content_tracing');。实现在 electron_api_content_tracing.cc(336 行,没有独立头文件),注册段在 :322-336:
void Initialize(v8::Local<v8::Object> exports, ...) {
gin_helper::Dictionary dict{isolate, exports};
dict.SetMethod<&GetCategories>("getCategories");
dict.SetMethod<&StartTracing>("startRecording");
dict.SetMethod<&StopRecording>("stopRecording");
dict.SetMethod<&GetTraceBufferUsage>("getTraceBufferUsage");
}
NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_content_tracing, Initialize)
四个方法分别落到 content::TracingController:GetCategories(:196-212)、StartTracing(:257-289)、StopTracing(:150-169)、GetTraceBufferUsage(:306-319)。所有四个都有 Browser::Get()->is_ready() 前置检查(:176-180、:200-204、:219-223、:310-314),所以 contentTracing 不能用来测 ready 之前的启动阶段——这正是 23.1.8 说"Electron 没有启动耗时打点"之后必须另找手段的原因。spec/fixtures/crash-cases/content-tracing-before-ready/ 这个 fixture 名字就是该限制的注脚。
23.9.2 TraceConfig 转换器有两条 FromV8 路径
:74-101:
template <>
struct Converter<base::trace_event::TraceConfig> {
static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
base::trace_event::TraceConfig* out) {
gin_helper::Dictionary options;
if (ConvertFromV8(isolate, val, &options)) {
std::string category_filter, trace_options;
if (options.Get("categoryFilter", &category_filter) &&
options.Get("traceOptions", &trace_options)) {
*out = base::trace_event::TraceConfig(category_filter, trace_options);
return true;
}
}
base::DictValue memory_dump_config;
if (ConvertFromV8(isolate, val, &memory_dump_config)) {
*out = base::trace_event::TraceConfig(memory_dump_config);
return true;
}
return false;
}
};
trace-config.md:3-34 逐字段列出 recording_mode、trace_buffer_size_in_kb(默认 100 MB)、trace_buffer_size_in_events、enable_argument_filter、included_categories、excluded_categories、included_process_ids、histogram_names、memory_dump_config,以及 Electron 私有扩展 nativeHeapProfiling。trace-categories-and-options.md:3-26 则给出旧式字段:categoryFilter 支持 - 前缀排除,traceOptions 的 record-until-full / record-continuously / trace-to-console 三者互斥、enable-sampling 优先。
23.9.3 Perfetto protobuf,且不再支持 JSON
StartTracing(:270-282)是格式断代的关键:
electron_api_content_tracing.cc:271-278
// Recordings always use the Perfetto protobuf format.
perfetto::TraceConfig perfetto_config = tracing::GetDefaultPerfettoConfig(
trace_config, /*privacy_filtering_enabled=*/false,
/*convert_to_legacy_json=*/false);
if (heap_profiler_options) {
AddHeapProfilingDataSource(trace_config, *heap_profiler_options,
&perfetto_config);
}
if (!instance->StartTracingWithPerfettoConfig(
perfetto_config,
base::BindOnce(gin_helper::Promise<void>::ResolvePromise,
std::move(promise)))) {
content-tracing.md:93-95 写明 "The legacy JSON format is no longer supported"。这直接影响工具链:老一代用 chrome://tracing 打开 JSON 的脚本、基于 traceEvents 数组做的分析器全部失效,得换成 Perfetto UI 或 trace_processor。
spec/api-content-tracing.spec.ts:1-60 为此专门用 protobufjs 内联定义了一份 TracePacket / TrackEvent / LegacyEvent / StackSample 的 schema,注释(:15-17)说明测试工程里没有 Chromium 源码树可依赖;:234-239 用"首字节不是 { 且有 packet"来断言产出的是 protobuf。
StopTracing(:150-169)用 TracingController::CreateFileEndpoint(...) 落盘,content-tracing.md:83-121 说 stopRecording([resultFilePath]) 不传路径时返回系统 temp 目录下的文件路径。spec/api-content-tracing.spec.ts:309-343 覆盖自动生成路径、空路径、"no trace in progress" 三种情况;:274-278 覆盖二次 stop 被拒。
23.9.4 nativeHeapProfiling:Electron 加的私有数据源
nativeHeapProfiling 不是 Chromium TraceConfig 的标准字段,Electron 在 :233-247 先从 options 里摘出来,再由 :107-128 的 AddHeapProfilingDataSource() 往 perfetto_config 加一个数据源,用 tracing::kNativeHeapProfilerSourceName + ChromiumSamplingHeapProfilerConfig,并按 included_process_ids 设置 producer_name_filter。
native-heap-profiler-options.md:3-11:dumpInterval 默认 0(表示停止时只取一次快照)、samplingInterval 默认 131072 字节(128 KiB)且必须大于 0。spec/api-content-tracing.spec.ts:242-272 测非法参数抛错、:388-446 测 stack samples 与 V8 samples 都能出现在 trace 里。
这是本树里唯一一处把采样堆剖析与时间线 trace合并到一个会话的能力,排查 native 内存增长时比单独落堆快照更有用,因为它能看到分配发生在哪个阶段。
23.9.5 electron 类别与缓冲区
content-tracing.md:50-51 指出 Electron 加了一个非默认类别 "electron"。源码里对应大量 TRACE_EVENT*("electron", ...),例如 node_bindings.cc:693 的 TRACE_EVENT0("electron", "NodeBindings::Initialize")、electron_api_context_bridge.cc:482 等。这意味着:不显式包含 electron 类别时,你看不到 Electron 自己的埋点,只能看到 Chromium 与 Blink 的事件。做启动分析时 included_categories 至少要含 electron、toplevel、base、v8 这几族。
getTraceBufferUsage()(:306-319)返回 value / percentage,spec/api-content-tracing.spec.ts:347-384 断言无 trace 时 percentage === 0。默认 100 MB 环形缓冲在长时间采样下会被覆盖,所以 traceOptions: 'record-until-full' 适合抓启动段,record-continuously 适合抓稳态但必须自己控制停止时机。
23.10 Node 的 trace_event 如何汇入 Chromium 的 Perfetto
23.10.1 十个补丁的分工
这是本章最能体现"缝合"主题的一节。Node 24 上游引入了自己的 Perfetto SDK tracing agent,会创建进程内 backend、独立会话、写 pftrace 文件;而 Chromium 已经持有一个进程级 Perfetto client。两者并存意味着同一个进程里两套追踪基础设施、两套类别过滤、两份输出,且 contentTracing 管不到 Node 那套。仓库用十个补丁解决这件事:
| 补丁 | 作用 |
|---|---|
build_perfetto-sdk.patch:105 (237 行) | 构建层:v8_use_perfetto 可被外部覆盖、--with-perfetto、链接 perfetto_sdk、定义 V8_USE_PERFETTO_SDK |
fix_use_embedder_perfetto_client_when_available.patch (396 行) | 链路核心:嵌入模式下不创建 Node agent,改把 Node 的 TrackEvent 注册到 Chromium client |
lib_add_perfetto_support.patch (379 行) | JS 层重写 lib/internal/trace_events.js,按 usePerfetto 切换类别串与 phase 字母 |
src_add_perfetto_trace_agent.patch (1131 行) | 新增 Node 自己的 Perfetto agent 与 20 个类别的注册表(独立 Node 二进制用) |
src_fix_perfetto_build_on_gettracefilepath.patch (159 行) | 移除旧 node_trace_buffer/writer,抽出公共 GetTraceFilePath() |
src_fix_trace_macro_compatibility.patch (132 行) | 修 fs 同步 trace 宏在 Perfetto 下的 phase 兼容 |
src_test_disable_trace_events_tests_when_perfetto_is_enabled.patch (526 行) | 给约 30 个旧 test-trace-events-* 加 skip 条件 |
chore_register_node_as_a_dynamic_trace_category_prefix.patch:4-24 (27 行) | Chromium 侧把 node 注册为动态类别前缀 |
src_use_legacy_trace_macros_in_perfetto_to_support_all_phases.patch (98 行) | V8 BUILTIN(Trace) 改用 legacy shim 以支持任意 phase |
test_accomodate_v8_thenable_stack_trace_change_in_snapshot.patch (33 行) | 与 Perfetto 无关,纯 V8 thenable 栈快照适配 |
最后一行与 Perfetto 无关,只适配 V8 thenable 栈快照;test_disable_trace_events... 实际带 src_ 前缀。
23.10.2 核心分流的那一段
fix_use_embedder_perfetto_client_when_available.patch:6-20 的提交说明,是整条链路最值得整段引用的文字:
Node.js v24.19.0 introduces a standalone perfetto SDK tracing agent which initializes an in-process backend, creates independent tracing sessions, and writes pftrace files. Electron already owns a process wide perfetto client through Chromium, so creating Node.js owned clients in browser, renderer processes duplicates tracing infrastructure and produces recording state independent of contentTracing. ... For embedded Electron processes, do not create Node.js tracing Agent. Instead, register Node.js TrackEvent data source with Chromium perfetto client. This preserves
node.*event emission while allowing contentTracing to remain the sole owner of category filtering, recording sessions, output, and lifecycle.
代码在 :95-101(src/node.cc 的 InitializeOncePerProcessInternal):
fix_use_embedder_perfetto_client_when_available.patch:357-362
+#if defined(V8_USE_PERFETTO)
+ // Register Node's TrackEvent data source when tracing is provided by the
+ // embedder. The standalone tracing agent initializes and registers it later.
+ if (perfetto::Tracing::IsInitialized()) {
+ tracing::RegisterPerfettoTrackEvent();
+ }
+#endif
perfetto::Tracing::IsInitialized() 就是判据:Chromium 已经初始化过,说明这是嵌入模式。:351-367 的 RegisterPerfettoTrackEvent() 调到 node::TrackEvent::Register();:260-279 的 Agent::CreateDefault() 用 #if NODE_USE_PERFETTO_SDK 包住 new PerfettoTracingAgent(),嵌入模式下直接 CHECK(false);:179-257 给所有 Agent::GetInstance() 调用点加判空,因为不再有 agent。:22-32 的 node.gni 把 node_use_perfetto_sdk = true 限定为仅 ELECTRON_RUN_AS_NODE 时保留——回忆 23.1.1,那正是"纯 Node 启动路径",那里确实需要 Node 自己的 agent。
于是 ELECTRON_RUN_AS_NODE 在这里第二次成为分叉点:它既决定走不走 Chromium 启动,也决定用哪套 Perfetto client。
23.10.3 类别注册与动态前缀
src_add_perfetto_trace_agent.patch:918-974 新建 src/tracing/trace_event_perfetto.h,:945-968 用 PERFETTO_DEFINE_CATEGORIES_IN_NAMESPACE(node, ...) 列出 node、node.async_hooks、node.environment、node.fs.sync、node.perf.event_loop、node.console、node.http 等 20 个类别。
Chromium 侧那 27 行补丁(:16-27)只加了一个词:
PERFETTO_DEFINE_TEST_CATEGORY_PREFIXES("cat",
"test",
"test_gpu",
"kTest",
+ "node",
"noise",
提交说明(:6-14)解释了为什么用动态前缀而不是静态注册:静态注册会超过 ValidateCategories() 的 constexpr 递归深度 512。这是一条非常具体的上游限制,也是"一个词的补丁"能成为必需的原因。
另外 fix_use_embedder...patch:148-175 在 src/node_internals.h 里把 TRACING_CATEGORY_NODE1/2 从 "node,node.xxx,node.xxx.yyy" 这种多类别串改成单类别 "node.xxx",并把 NODE_TRACE_CATEGORY_ENABLED 映射到 Perfetto 版的 TRACE_EVENT_CATEGORY_ENABLED。多类别串在 legacy trace 里是合法的,在 Perfetto 的类别模型里不是。
23.10.4 JS 层的 phase 字母切换
lib_add_perfetto_support.patch:152-213 新建的 lib/internal/trace_events.js:
const { getCategoryEnabledBuffer, trace, usePerfetto } = internalBinding('trace_events');
let nodeTraceEventCategory;
if (usePerfetto) {
nodeTraceEventCategory = (category) => `${category}`;
} else {
nodeTraceEventCategory = (category) => `node,${category}`;
}
// Developer note: V8 `trace` API does not support async marks in perfetto yet.
const kAsyncBegin = usePerfetto ? CHAR_UPPERCASE_B : CHAR_LOWERCASE_B;
const kAsyncEnd = usePerfetto ? CHAR_UPPERCASE_E : CHAR_LOWERCASE_E;
const kTraceCount = usePerfetto ? CHAR_LOWERCASE_N : CHAR_UPPERCASE_C;
usePerfetto 由 C++ 注入(:349-365 的 NodeCategorySet::Initialize,#if defined(V8_USE_PERFETTO) 下设 True)。改动波及 lib/internal/console/constructor.js、http.js、perf/usertiming.js、util/debuglog.js、trace_events_async_hooks.js 等;src/node_constants.cc:339-345 删掉三个 Perfetto 不支持的 phase 常量。
src_fix_trace_macro_compatibility.patch:16-33 把 FS_DIR_SYNC_TRACE_BEGIN/END 这一对合并成单个 TRACE_EVENT0(Perfetto 下 TRACE_EVENT_END 不接受 name 参数),:120-129 在 node_file.cc 里对 V8_USE_PERFETTO 分支去掉 TRACE_NAME(syscall)。这些都是"宏语义不完全兼容"的补丁式修补。
src_use_legacy_trace_macros_in_perfetto_to_support_all_phases.patch:6-22 说明 V8 的 BUILTIN(Trace) 改用 INTERNAL_TRACE_EVENT_ADD / INTERNAL_TRACE_EVENT_ADD_WITH_ID 转发,以支持 Node 需要的 nestable async b/e/n 与 counter C phase,代价是清掉 TRACE_EVENT_FLAG_COPY、把 GLOBAL instant 降级成 THREAD(:28-94)。这是"为了兼容而损失一点语义"的一处,文档里不会写。
23.10.5 完整链路与回归证据
串起来是:构建开关 → node.* 类别注册 → JS/V8 层 phase 转发 → 嵌入模式不建 agent 只注册 TrackEvent → contentTracing 独占会话与过滤,最终 node.perf.usertiming 落在同一份 .pftrace 里。
spec/api-content-tracing.spec.ts:450-470 是端到端回归:
describe('node trace categories', () => {
it('captures performance.mark() as instant trace events', async () => {
await contentTracing.startRecording({
included_categories: ['node.perf.usertiming']
});
performance.mark('test-trace-mark');
const resultPath = await contentTracing.stopRecording();
const markEvents = getTraceEvents(resultPath).filter(
(event) => hasCategory(event, 'node.perf.usertiming') && event.name === 'test-trace-mark'
);
expect(markEvents.length, ...).toBeGreaterThanOrEqual(1);
:220-231 从反方向验证:excluded_categories: ['*'] 时 node.environment 不出现,证明 Node 类别确实受 contentTracing 的过滤控制,而不是从旁路写出去的。这两条测试合起来才证明"汇入"而不只是"共存"。
spec/chromium.spec.ts:909-915 还留了一条相关注释:v8_use_perfetto 与 node.async_hooks 类别在 --trace-startup 下有坑,测试里显式用 -node.async_hooks 排除——这是下一节要展开的。
23.11 测启动:仓库里真正可用的开关
23.11.1 --trace-startup 是 Chromium 继承的,不是 Electron 的
spec/chromium.spec.ts:900-921 是本树唯一一处使用启动追踪的地方:
describe('--trace-startup switch', () => {
const outputFilePath = path.join(app.getPath('temp'), 'trace.json');
...
const rc = await startRemoteControlApp([
'--trace-startup="*,-node.async_hooks"',
`--trace-startup-file=${outputFilePath}`,
'--trace-startup-duration=1',
'--enable-logging'
]);
三个参数分别控制类别过滤、输出文件、采集时长(秒)。--trace-startup 的解析实现属于 Chromium content 层,不在本仓库;本树只有这个 spec 与 trace-config.md:58 提到的 memory_infra_startup_tracing 链接。cherry-pick-63c916f7b401.patch:585 里能看到上游 InitStartupTracingForDuration() 的声明。
注意类别串里的 -node.async_hooks:这个类别在启动期事件量极大,会把 1 秒的缓冲冲满,所以测试主动排除。这从侧面印证了 23.10 的补丁确实让 Node 类别进入了同一条 trace。
--trace-startup-file 写出的后缀沿用旧名 trace.json,但产出格式由同时期的 Perfetto 配置决定;不要按文件名推断内容格式(对照 23.9.3)。
23.11.2 两个 Electron 私有的启动诊断变量
| 变量 | 位置 | 作用 | 是否改变被测路径 |
|---|---|---|---|
ELECTRON_PROFILE_INIT_SCRIPTS | electron_browser_client.cc:698-701 | 给子进程追加 --profile-electron-init,把 renderer init 推迟一个 tick 供 profiler 挂载 | 改变(bundle.mjs:250-258、targets.mjs:19-30,仅 renderer) |
ELECTRON_LOG_ASAR_READS | environment-variables.md:214-220 | 把读 asar 的 offset 与路径写到 os.tmpdir()/<name>-access-log.txt,用于优化归档内文件排布 | 改变(额外文件写) |
后一条的文档注释很关键:"This variable is read once when each process starts"。第 22 章 22.4 讲过调用点只有 asar-fs-wrapper.ts:1316 与 :1379 两处,输出格式是 <offset>: <path>。把它按启动顺序排一遍,就能看出冷启动实际读了归档里哪些文件、顺序如何,进而用 asar 的 ordering 把热文件放前面。这是本章唯一一条由源码直接支持的应用侧启动 I/O 优化,而且它不依赖任何计时 API。
23.11.3 按"是否扰动被测对象"给手段分类
| 手段 | 覆盖阶段 | 扰动 | 能回答什么 |
|---|---|---|---|
--trace-startup | 阶段 1 起,含 native | 低(trace 本身有开销,但不改执行顺序) | 各阶段墙钟时间、谁在阻塞 |
ELECTRON_LOG_ASAR_READS | 阶段 7–10 的归档读取 | 中(额外文件写) | 冷启动读了哪些文件、顺序 |
ELECTRON_PROFILE_INIT_SCRIPTS | renderer init | 高(推迟一个 tick) | init bundle 的 CPU 热点 |
contentTracing | ready 之后 | 中(环形缓冲 + 类别过滤) | 稳态事件、Node/Chromium 合流时间线 |
app.getAppMetrics() | ready 之后 | 中(Linux 同步读 /proc) | 进程级 CPU/内存快照 |
performance.now() in whenReady | 仅阶段 9 之后 | 无 | 只有 JS 执行耗时,不是冷启动 |
这张表是 23.16 方法论的输入。最后一个陷阱再强调一次:把 ELECTRON_PROFILE_INIT_SCRIPTS=1 下测出的首帧时间当作基线,会系统性高估,因为那个 tick 是专为 profiler 加的。
23.12 OOM:两条路径与一组 crash keys
本树没有旧资料里的单一 OnOOM 回调,取而代之的是两条互补路径。
路径一:近堆上限回调。 oom_stack_trace.h:12-13 只暴露 RegisterOomStackTraceCallback / UnregisterOomStackTraceCallback;实现在 oom_stack_trace.cc:106-109(211 行),注册点 renderer_client_base.cc:415-420(DidCreateScriptContext)、:631(worker)、:638(注销)。:187-209 用 isolate->AddNearHeapLimitCallback(NearHeapLimitCallback, raw) 挂回调,OomState 继承 gin::PerIsolateData::DisposeObserver 并带 std::atomic<bool> is_in_oom 保证幂等。
:127-183 的回调做四件事:is_in_oom.exchange(true);记录 Heap: used=..MB limit=..MB;调 v8_oom::RecordHeapDiagnostics();RequestInterrupt(CaptureStackOnInterrupt, state) 后移除自身,并抬高 kHeapBump = 20MB 堆上限给中断留空间。:166-180 还处理指针压缩 cage(kPtrComprCageReservationSize == 1<<32)时钳制失效的兜底。
为什么不直接抓栈?:90-125 的 CaptureStackOnInterrupt() 注释给了答案:V8 只能在 safe point 展开栈,回调发生时可能停在优化帧里、没有 deopt info,强抓会 FATAL。所以先请求中断,等 V8 到安全点再取 StackTrace::CurrentStackTrace(isolate, 10)。中断里还有一道保护:
oom_stack_trace.cc:106-109
constexpr size_t kMinHeadroom = 2 * 1024 * 1024; // 2 MB
if (stats.used_heap_size() + kMinHeadroom > stats.heap_size_limit()) {
LOG(INFO) << "Skipping JS stack capture: insufficient heap headroom";
return;
}
OOM 时不能为了诊断再分配内存,这条 2 MB 余量判据和 20 MB 抬升是同一个约束的两面。
路径二:v8::oom_error_callback。 node_bindings.cc:774-780 在 SetUpIsolate() 里设 is.oom_error_callback = V8OOMErrorCallback;回调本体在 :203-224:
void V8OOMErrorCallback(const char* location, const v8::OOMDetails& details) {
const char* message =
details.is_heap_oom ? "Allocation failed - JavaScript heap out of memory"
: "Allocation failed - process out of memory";
...
#if !IS_MAS_BUILD()
// TryGetCurrent() instead of GetCurrent() to avoid FATAL if no isolate.
v8::Isolate* isolate = v8::Isolate::TryGetCurrent();
electron::v8_oom::RecordErrorDetails(isolate, location, details);
electron::v8_oom::RecordHeapDiagnostics(isolate);
#endif
OOM_CRASH(0);
}
v8_oom_diagnostics.cc:131(145 行)是崩溃键的落点::22-36 用 std::atomic<const void*> g_owner 的 ClaimFor() 保证第一个 OOM 的 isolate 独占 crash keys(多 isolate 同时 OOM 时避免互相覆盖);:48-103 写入 electron.v8-oom.heap.used/total/limit/total_available/total_physical/malloced_memory/external_memory/native_contexts/detached_contexts/utilization_pct/old_space.*/lo_space.*;:126-133 用 CrashKeyString<20320> 存 electron.v8-oom.stack。.h:15-19 注释明确"固定静态存储、OOM 回调里不分配内存";MAS 构建下这些全是空实现(:135-143)。
spec/api-crash-reporter.spec.ts:340-375 用 --js-flags=--max-old-space-size=128 触发渲染器、JSON.stringify、web worker 三处 OOM,断言 crash['electron.v8-oom.stack'] 含 oomTrigger、heap.used / heap.limit 为字符串。这是第 20 章崩溃报告机制在堆耗尽场景的具体兑现。javascript_environment.cc:256-264 把 --js-flags 拼上 --no-freeze-flags-after-init 后 v8::V8::SetFlagsFromString,:170-185 说明 max_young_generation_size 要配合 v8.setHeapSnapshotNearHeapLimit() 调整;process.takeHeapSnapshot 的实现在 heap_snapshot.cc:46-60(23.8.5)。
至于内存压力:shell/ 下检索 MemoryPressureListener / MemoryPressureMonitor 只命中 electron_api_web_frame.cc:899-903 的 ClearCache() 主动广播 MEMORY_PRESSURE_LEVEL_CRITICAL——是广播而非注册监听器,shell/common/ 与 shell/browser/ 里没有任何监听者。
23.13 稳态资源:节流、GPU 与进程数
23.13.1 backgroundThrottling 的三层实现
background_throttling_source.h:10-14 只有四个成员的纯虚接口 GetBackgroundThrottling()。WebContents 继承它(electron_api_web_contents.h:141),默认值 background_throttling_ = true(.h:919),从 webPreferences 读(:1033)。
首次应用(:2303-2309):
electron_api_web_contents.cc:2303-2308
if (!background_throttling_)
render_frame_host->GetRenderViewHost()->SetSchedulerThrottling(false);
auto* rwh_impl =
static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost());
if (rwh_impl)
rwh_impl->disable_hidden_ = !background_throttling_;
运行时改(:3139-3174 的 SetBackgroundThrottling)遍历 ForEachRenderFrameHostWithAction,对每个 frame 设 disable_hidden_ 并调 SetSchedulerThrottling(allowed);:3176-3182 还在 !allowed && IsHidden() 时通过 view 反隐藏。绑定暴露在 :5767-5772,JS 侧是 contents.backgroundThrottling 属性(web-contents.md:2542)。
SetSchedulerThrottling 和 disable_hidden_ 都不是 Chromium 上游 API,来自两个补丁:allow_disabling_blink_scheduler_throttling_per_renderview.patch(改 11 个文件,给 page.mojom 加 SetSchedulerThrottling)、fix_disabling_background_throttling_in_compositor.patch:14-50(给 ui::Compositor 加 SetBackgroundThrottling,核心是 display_private_->SetDisplayVisible(background_throttling_ ? host_->IsVisible() : true))。第三个补丁 revert_remove_the_allowaggressivethrottlingwithwebsocket_feature.patch 恢复 AllowAggressiveThrottlingWithWebSocket——关掉节流却仍被激进节流的常见原因就在这里。
23.13.2 多源聚合是 AND,不是 OR
native_window.cc:796-825:
void NativeWindow::UpdateBackgroundThrottlingState() {
if (!widget() || !widget()->GetCompositor()) return;
bool enable_background_throttling = true;
for (const auto* background_throttling_source :
background_throttling_sources_) {
if (!background_throttling_source->GetBackgroundThrottling()) {
enable_background_throttling = false;
break;
}
}
widget()->GetCompositor()->SetBackgroundThrottling(
enable_background_throttling);
}
容器是 absl::flat_hash_set<BackgroundThrottlingSource*>(native_window.h:595-596),增删在 WebContents 的 SetOwnerWindow / 析构(:1372、:3064、:3071)。语义很清楚:只要窗口内有一个 webContents 关了节流,整个窗口的合成器就不节流、持续画帧。web-preferences.md:82-88 与 browser-window.md:116-133 都点明了这个"一票否决":关掉节流后 Page Visibility 会一直保持 visible,即使窗口最小化或被遮挡。这对后台 CPU/GPU 占用是直接影响,而且影响范围比"我这个页面"大得多。
一个必须纠正的社区说法:本仓库(含 patches/)检索 disable-background-timer-throttling、background-timer、kDisableBackgroundTimer、TimerThrottling 全部零命中。实际存在的是 --disable-renderer-backgrounding(command-line-switches.md:56-63,作用是"防止 Chromium 降低不可见页面渲染进程的优先级",不是关定时器),spec 里用在 spec/api-web-contents.spec.ts:2582、spec/api-ipc.spec.ts:1194-1196、spec/cpp-heap.spec.ts:1433。按不存在的开关调优,等于什么都没做。
23.13.3 GPU 状态、spare renderer 与 utility 进程
app.getGPUFeatureStatus() 的实现只有一行(electron_api_app.cc:1564-1566):return gin::ConvertToV8(isolate, content::GetFeatureStatus());,文档 app.md:1551-1556 要求只能在 gpu-info-update 事件之后用;gpu-feature-status.md:3-29 列出 13 个字段与 10 种取值(disabled_software / enabled_force / unavailable_software 等),spec/api-app.spec.ts:2164-2170 断言 webgl / gpu_compositing 为字符串。相邻的 GetGPUInfo()(:1568-1580)走 content::GpuDataManagerImpl。
--in-process-gpu / --single-process 在本树源码、文档、补丁里零命中(唯一相似字符串是 sandbox.md:23 的锚文本,语义无关);它们若生效是 Chromium 自身行为,Electron 没有适配。
真正会改变进程数、且能在本树验证的有两处:23.1.2 提到的 SpareRendererForSitePerProcess(常驻一个备用渲染器,spec/api-web-contents.spec.ts:2575-2603 用 getAppMetrics() 追踪 pid);以及 utilityProcess——electron_api_utility_process.cc:229-259 用 content::ServiceProcessHost::Launch() 启动,默认显示名 Node Utility Process,随后经 electron_api_app.cc:831-837 进入 app_metrics_(23.7.1)。spec/api-web-contents.spec.ts:4674-4687 还用同一手法观察跨进程导航时 renderer pid 的变化。用 getAppMetrics() 反查进程模型,是这套指标 API 比"看内存"更有价值的一种用法。
23.14 有一个 MetricsService,但它不上报
electron_metrics_service_client.cc:22-34 确实创建了 Chromium 的 UMA 服务:
ElectronMetricsServiceClient::ElectronMetricsServiceClient()
: metrics_state_manager_(metrics::MetricsStateManager::Create(
g_browser_process->local_state(), this, std::wstring(),
base::FilePath(), metrics::StartupVisibility::kUnknown)),
metrics_service_(std::make_unique<metrics::MetricsService>(
metrics_state_manager_.get(), this,
g_browser_process->local_state())) {
RegisterMetricsServiceProviders();
}
browser_process_impl.cc:193 在 PreCreateThreads() 里创建这个 client,:539-541 只是 make_unique。但把上报链路逐环查完,结论是完全禁用:
| 环节 | 位置 | 值 |
|---|---|---|
| 同意状态 | electron_metrics_service_client.cc:108-110 | IsConsentGiven() 恒 false |
| 上传间隔 | :104-106 | base::TimeDelta::FiniteMax() |
| uploader | :94-102 → electron_metrics_log_uploader.cc:17-24 | 空实现,回调恒 net::ERR_NOT_IMPLEMENTED |
| 服务管理器 | browser_process_impl.cc:213-216 | GetMetricsServicesManager() 返回 nullptr |
| brand / channel | :71-78 | GetBrand() 为 false,channel 恒 UNKNOWN |
| synthetic trial registry | :44-47 | nullptr |
检索 EnableMetricsService、IsMetricsReportingEnabled、metrics_service()->Start、EnableReporting 在 shell/ 下零命中。唯一注册的 provider(electron_metrics_service_client.cc:112-115)是 ElectronBackgroundTracingMetricsProvider,而它(:22-32)只覆写 RecordCoreSystemProfileMetrics(),往 SystemProfileProto 里填版本与 locale——给 trace 补元数据,不是上报。electron_tracing_delegate.cc:45-52 同理,把 product-version / os-name 写回 ChromeEventBundle 元数据,因为 catapult 的 symbolize_trace 需要。
所以这个对象存在的唯一理由是让 background tracing 的基础设施有地方挂 SystemProfileProto。第 20 章讲 crashReporter 时说过 Electron 的崩溃上报是显式 start() 才启用,这里补上另一侧:UMA 连 start() 都没有,且上传器是硬编码空实现。任何"Electron 会偷偷上报性能数据"的担心,在这份源码里找不到依据;反过来,任何"我有 UMA 数据可以看启动指标"的期待,同样落空。可用的只有 23.9–23.11 那些本地 trace 与 23.6–23.8 的本地指标。
23.15 十五个常见误解
误解 1:Electron 提供启动耗时指标。
shell/ 下没有任何主进程启动计时(TimeTicks 命中全在网络超时与 UI 动画),没有 StartupTimer / UMA_HISTOGRAM_TIMES。官方只给 Chrome Tracing(23.1.8)。在 app.whenReady() 里用 performance.now() 测到的是 JS 执行耗时,不含 native 阶段。
误解 2:打开 loadBrowserProcessSpecificV8Snapshot 一定更快。
恰恰相反:fuses.md:125-129 明说主进程用自定义快照后会从源码 bootstrap Node 环境,"costs part of the main-process startup time the embedded snapshot otherwise saves"。链路见 23.2.7。
误解 3:node_use_node_snapshot 在 Electron 里一直开启。
补丁主题是 Re-enable(electron_enable_node_startup_snapshot_generation_in_chromium_s_v8.patch:4-8),上游原本有一段禁用注释,本版本才重新启用(23.2.2)。
误解 4:内部 bundle 靠 webpack 分块懒加载。
bundle.mjs:177 是 rolldown,:217 codeSplitting: false,单 chunk 且有断言。懒加载靠 nodeExternalsPlugin 把内置模块包成 CJS shim(:146-175),懒的是 require() 时机(23.3.1–23.3.2)。
误解 5:package.json 的 v8Flags 早点应用没区别。
lib/browser/init.ts:98 的注释写明"Applied only now so that everything above still matched its code cache"。提前一行就可能让整个内部 bundle 的构建期缓存失效(23.1.7)。
误解 6:预推的启动数据靠 ack / barrier 保证先到。
靠的是 GetRemoteAssociatedInterfaces() 与 content.mojom.Frame 共通道的 mojo 顺序语义(electron_api_web_contents.cc:2822-2828),没有显式同步。换成独立管道即失效(23.4.4)。
误解 7:nodeIntegration 窗口也能吃到持久化的 preload code cache。
renderer_startup_data.cc:89-93 对这类 frame 直接 return,浏览器进程连内容都不读——注释说"reading them here would be wasted work"(23.4.3、23.4.7)。
误解 8:percentCPUUsage 是当前瞬时 CPU 占用。
它是自上次调用以来的平均值(cpu-usage.md:11-12),且被 NumberOfProcessors() 除过(electron_api_app.cc:1505)。8 核上跑满单核约显示 12.5%。
误解 9:只读某一个 pid 就不会影响别的进程。
getAppMetrics() 是遍历 app_metrics_ 的循环,每调一次所有进程的 base::ProcessMetrics 快照都被刷新(23.7.3)。它与 process.getCPUUsage() 又是两套独立区间(23.7.5)。
误解 10:Windows 上 idleWakeupsPerSecond === 0 说明进程不唤醒。
electron_api_app.cc:1507-1515 与 electron_bindings.cc:275-299 都因底层方法会打 NOTIMPLEMENTED 警告而直接填 0。这是哨兵值,不是测量值。
误解 11:process.getHeapStatistics() 是 Node 原生 API。
Node 原生的是 v8.getHeapStatistics();Electron 在 BindProcess 里显式挂到 process 上(electron_bindings.cc:43-70),为的是让沙箱渲染器也能读(23.8.2)。
误解 12:process.getIOCounters() 还能用。
docs/breaking-changes.md:1342-1344 已标记移除,原因是 Chromium 不再提供该信息;process.resourceUsage 则从未被 Electron 覆盖,属 Node 原生(23.8.6)。
误解 13:contentTracing 能抓到 ready 之前的启动段。
四个方法全有 Browser::Get()->is_ready() 前置检查(electron_api_content_tracing.cc:176-180 等)。启动段只能用 --trace-startup(23.9.1、23.11.1)。
误解 14:trace 输出还能当 JSON 读。
:270-274 固定 convert_to_legacy_json=false,content-tracing.md:93-95 明说 legacy JSON 不再支持,产出是 Perfetto protobuf(23.9.3)。
误解 15:Electron 会上报 UMA,且 OOM 走 OnOOM 回调。
MetricsService 对象存在但 IsConsentGiven() 恒 false、上传间隔 FiniteMax()、uploader 恒 ERR_NOT_IMPLEMENTED(23.14);OOM 是 AddNearHeapLimitCallback + oom_error_callback 双路径(23.12)。另外常被推荐的 --disable-background-timer-throttling 在本仓库含 patches/ 零命中,实际存在的是 --disable-renderer-backgrounding(23.13.2)。
23.16 一套可复现的测量方法,与本章收束
把全章的证据收成一条自己能跑的链。四步,每一步都对应前面某一节,且明确标注它的扰动:
第一步:进程外计时。 由父进程记录 spawn 到"窗口真的画出来"的墙钟。不要用应用内 performance.now()(23.1.6)。重复冷启动(清 OS 文件缓存)与热启动各取足够样本,分别统计,不要混在一起——23.4 的 asar 冷读、23.3 的 code cache 命中都受页缓存影响。
第二步:切分 native 阶段。 用 spec/chromium.spec.ts:900-921 那组参数跑 --trace-startup="*,-node.async_hooks" + --trace-startup-file + --trace-startup-duration=1,在 Perfetto 里按 23.1.9 的阶段表切分。记得同时包含 electron 类别,否则看不到 Electron 自己的埋点(23.9.5)。
第三步:定位启动 I/O。 用 ELECTRON_LOG_ASAR_READS=1 导出 <offset>: <path> 访问日志,按首次出现顺序整理归档内热文件,调整 asar ordering。这一步只扰动"额外写一份日志",不改执行顺序(23.11.2)。若要抓 renderer init 的 CPU 热点,另开 ELECTRON_PROFILE_INIT_SCRIPTS=1,但那次的数字不能进基线(23.3.5)。
第四步:稳态用固定间隔,而不是高频轮询。 主进程里可以这样起一条采样线:
const { app } = require('electron');
let prev = null;
app.whenReady().then(() => {
app.getAppMetrics(); // 丢弃首次读数:区间从进程启动算起
setInterval(() => {
const snap = app.getAppMetrics();
const byPid = new Map(snap.map((m) => [m.pid, m]));
if (prev) {
for (const [pid, m] of byPid) {
const before = prev.get(pid);
if (before) {
// 单位:KB;percentCPUUsage 是本区间平均且已除以核数
const deltaRSS = m.memory.workingSetSize - before.memory.workingSetSize;
console.log(pid, m.type, m.cpu.percentCPUUsage, deltaRSS);
}
}
}
prev = byPid;
}, 5000).unref();
});
要点全在注释与前三节里:丢弃首次读数、固定间隔、每次都取整表(不要按 pid 过滤后少调)、按 pid 自己关联历史(因为 ChildProcessDisconnected() 会 erase)、Windows 上忽略 idleWakeupsPerSecond、非 Windows 才有 sandboxed 语义。需要线程级热点时,另起一次 contentTracing.startRecording({ included_categories: ['electron', 'toplevel', 'v8', 'blink'] }),而不是提高上面这个定时器的频率。
三句话收束本章。
第一句:Electron 的启动优化几乎全是"把工作搬到构建期或搬到不阻塞的位置"。 V8/Node 快照把堆初始化与 Node bootstrap 搬进 node_mksnapshot(23.2),js2c code cache 把内部 bundle 的编译搬进 electron_natives_codecache(23.3),RendererStartupData 把 preload 的同步 IPC 搬到 ReadyToCommitNavigation 之前的 mojo 预推(23.4)。三者都不减少总工作量,只减少关键路径上的等待——因此它们全部依赖构建期与运行期逐字节配套:flags hash、只读堆 checksum、source hash、参数名注释,任何一处错配就静默退化成源码编译。
第二句:Electron 给的指标都是进程级快照,口径写在源码里而不是文档里。 getAppMetrics() 调用即重置全表区间、CPU 百分比被核数除过、Windows 的唤醒数是硬编码 0、Linux 每次同步读 /proc/<pid>/status、mac 靠 port provider 取 task_info;process.* 上六个入口有三个是 Electron 新增、一个已被移除、getProcessMemoryInfo 在三类名进程里由三套代码兑现。"量到了"与"量对了"是两件事,本章 23.6–23.8 花的主要篇幅就是后者。
第三句:唯一能串起全进程时间线的是 Perfetto,而这条线是补丁缝出来的。 十个补丁让 Node 的 node.* 事件放弃自己的 agent、注册到 Chromium 的 client,使 contentTracing 成为唯一会话所有者(23.10);代价是 V8 的 trace() builtin 得回退到 legacy shim、GLOBAL instant 降级成 THREAD。加上启动段还得靠 --trace-startup、ready 之前 contentTracing 不可用、UMA 被硬编码禁用,结论是:Electron 没有"开箱即得的性能报表",只有一组口径各异的原语和一条需要自己拼的时间线。第 22 章末尾说这一章要"逐项量化开销",读到这里应当修正为——能精确量化的是机制与边界,毫秒数必须由你在自己的机器、自己的应用上按上面四步测出来。
下一章第 24 章讲演进与展望,会把这 23 章里反复出现的那类"薄薄一层"——补丁、fuse、mojom 扩展、进程旁路——放回版本史里,看哪些是历史包袱、哪些正在被上游吸收,以及哪些会在下一个 Chromium 大版本里消失。