Skip to content

perf: cut first-window, ipc, contextBridge, Buffer and asar overhead (#52923) - #53019

Merged
MarshallOfSound merged 1 commit into
42-x-yfrom
bp/42-x-y/52923
Aug 19, 2026
Merged

MarshallOfSound merged 1 commit into
42-x-yfrom
bp/42-x-y/52923

Conversation

@codebytere

@codebytere codebytere commented Aug 19, 2026 •

Copy link
Copy Markdown
Member

Backport of #52923

See that PR for details. Trop could not cherry-pick it cleanly; the only conflicts were include lists that main has since pruned (#52469, #52566), and clang-format's older line breaking. The in-sandbox ArrayBuffer allocator commit ("give V8's in-sandbox allocator a PartitionAlloc backend outside renderers") is left out here: it installs itself through v8::V8::SetInSandboxAllocator(), which V8 only gained in the version that ships with 44-x-y, so Buffer.allocUnsafe() keeps its current cost on this line.

Notes:

  • Fixed a stall of tens of milliseconds while creating the first BrowserWindow on Linux.
  • Improved the performance of file lookups inside ASAR archives and of large files served from them to the renderer.
  • Improved the performance of calls through contextBridge-exposed APIs.
  • Reduced the main-thread cost of sending large values through ipcRenderer, ipcMain handlers and webContents.send.

@codebytere codebytere added backport This is a backport PR semver/patch backwards-compatible bug fixes 42-x-y labels Aug 19, 2026
@MarshallOfSound
MarshallOfSound enabled auto-merge (squash) August 19, 2026 09:15
…52923)

* perf: preallocate the file descriptor table before threads start (linux)

Linux grows a process's file descriptor table in powers of two on demand
and, once the table is shared with other threads, expand_fdtable() waits
for a full RCU grace period before freeing the old table. Whichever
open()/socket()/memfd call crosses the 64-descriptor boundary in an
already multi-threaded process eats that wait; in the browser process it
lands inside the first `new BrowserWindow` (the renderer's channel and
shared memory setup) and measured 55-115 ms of uninterruptible sleep in
openat() on a 64-vCPU host, 10-30 ms being typical elsewhere.

content's zygote already grows the table of every child it forks for this
reason (content/zygote/zygote_linux.cc). Do the same in main() for the
browser and the exec'd children: one F_DUPFD_CLOEXEC to descriptor 512
while the process is still single-threaded leaves a 1024-entry table
(8 KB) behind and nothing else. Where RLIMIT_NOFILE is lower the fcntl
fails and nothing changes.

* perf: stop rebuilding the whole path per component in asar::GetAsarArchivePath

GetAsarArchivePath() located the archive by calling DirName() once per
path component and MatchesExtension() on each intermediate path (a
BaseName() copy every time), then split the result with
AppendRelativePath(), which runs GetComponents() over both the parent
and the child. For a file inside app.asar that is dozens of string
allocations per lookup, and the fs wrapper performs this lookup
(asar.splitPath) for every fs call whose path mentions ".asar" - around
ten per require()'d module.

Scan the component boundaries as offsets into the existing string
instead, hand only the candidate component to MatchesExtension(), and
build the relative part with Append() from the components after the
match. The outputs are byte-identical to before, including the existing
corner cases (a real directory named *.asar is not an archive, the
deepest matching component wins, doubled separators and a leading "."
collapse the way Append() collapses them, a trailing separator on the
archive path itself is kept); new asar-spec cases pin those down.

* perf: keep context bridge proxy function state in the function's data array

The proxy that contextBridge installs for a function carried its target,
receiver and dynamic-property flag as three private properties on a state
object, so every call through the bridge did three v8::Private::ForApi
lookups (each allocating the key string) plus three GetPrivate calls
before it could invoke anything. Store the three values in a packed
v8::Array handed to v8::Function::New as the callback data and read them
back by index. The array is only reachable through the function's data
slot, exactly like the old state object, so nothing new becomes visible
to either world; the original-function marker on the proxy itself stays a
private property because that one has to live on a script-visible
object.

* perf: trim per-value work when the context bridge copies objects and arrays

Copying a plain object or array across the bridge visits every value, and
each visit paid for a trace event, three Blink wrapper probes
(WebElement, WebBlob, VideoFrame) that can only ever match API wrapper
objects, and, for object properties, an extra destination Context::Scope
enter/exit on top of the source one. Arrays were also filled with one
Set() per element.

Skip the Blink probes unless the value is an API wrapper object, drop the
inner trace event (the entry points keep theirs), read each property
under the source scope and define it under the destination scope that is
already active, and build array clones with the bulk v8::Array::New. The
values produced, the object cache and the recursion order are unchanged.

* perf: give V8's in-sandbox allocator a PartitionAlloc backend outside renderers

Node allocates Buffer.allocUnsafe(), Buffer.allocUnsafeSlow() and the
64 KB Buffer pool refill through ArrayBuffer::Allocator::NewDefaultAllocator()
(Electron's sandboxed-pointers patch), which under the V8 sandbox forwards
to V8's built-in in-sandbox allocator. V8 documents that allocator as a slow
placeholder embedders are expected to replace: it hands out page-granular
regions under a global mutex and zero-fills even "uninitialized" requests.
Blink replaces it for renderers (V8Initializer::InitializeInSandboxAllocator);
the browser, utility and ELECTRON_RUN_AS_NODE processes never did, so every
unpooled Buffer there paid a map/unmap round trip: Buffer.allocUnsafe of
1 MB ~300 us against ~12 us in a stock Node build, 64 KB ~30 us against
~2 us, and fs.readFile of a 1 MB file was several times slower than
reading into a preallocated buffer.

JavascriptEnvironment now installs an allocator with
v8::V8::SetInSandboxAllocator() before the isolate is created, backed by
gin's array buffer partition (which already lives inside the sandbox) the
same way Blink's is backed by its ArrayBufferContents partition.
PartitionAlloc refuses single allocations of ~2 GiB and more while the
placeholder had no such cap, so requests above PartitionAlloc's limit go to
the sandbox's address space directly (checked up front, so V8 never sees a
failed allocation to retry) and Buffer.allocUnsafe of 2 GiB and more keeps
working. Measured in the main process: allocUnsafe 64 KB 33 -> 5.6 us,
1 MB 297 -> 36 us, 4 MB 1691 -> 41 us, allocUnsafeSlow 1 MB 218 -> 13 us,
fs.promises.readFile 1 MB 1.2 -> 0.9 ms. Page zeroing moves from the
allocator to first touch, so a Buffer that is immediately written end to
end pays the same faults later instead.

* perf: serialize ipc values straight into the buffer they are sent in

Values passed through ipcRenderer.send/invoke/sendSync/sendToHost,
webContents.send, webFrameMain.send and their service worker equivalents
travel as blink.mojom.CloneableMessage. For payloads above mojo's 64 KB
inline limit that costs three fresh multi-megabyte buffers per hop: the
V8 serializer grows a zero-filled std::vector, mojo copies that into a
newly created shared memory region, and the receiving traits copy the
region back out into another vector before V8 reads a byte. In profiles
of 1-4 MB messages both main threads spent 30-40% of their time in page
faults for those buffers.

Electron owns both ends of these interfaces, so give them their own
payload type: electron.mojom.SerializedValue is a BigBuffer plus the
number of bytes written. The serializer keeps small values on the heap as
before and, once V8 asks for more than the inline limit, continues in the
shared memory region that will be sent, so the sender never holds a
second copy. On the receiving side a renderer parses the region in
place; the browser (and any other process) still parses a private copy,
because the sender keeps write access to shared memory while it is read.

MessagePort/postMessage paths keep blink's TransferableMessage, and the
CloneableMessage overloads stay for in-process users (contextBridge,
app 'second-instance' data).

The serializer moves to shared memory once V8's request shows the value
needs more than an inline message (not merely when the doubled request
crosses 64 KB), and grows regions 4x from there, so a value written in
many small pieces creates two or three regions rather than one per
doubling; each region is a brokered round trip for a sandboxed renderer
on Linux. Object-heavy payloads (arrays of small records) measure
renderer -> main 1 MB 10.2 -> 10.2 ms and 4 MB 41.5 -> 39.9 ms with this,
against +8% / +3% with per-doubling regions.

* perf: size protocol and asar response pipes to the body

Electron's URL loaders created their response data pipes with mojo's
64 KB default (the asar loader with a hard-coded 65536 copied from an old
FileURLLoader), so every response larger than that reached the renderer
in 64 KB slices, each one a producer wakeup on the browser main thread
plus a consumer wakeup in the renderer. Chromium since sized these up:
network::GetDataPipeDefaultAllocationSize() is 512 KB for ordinary loads
and 2 MB (kLargerSizeIfPossible) for file://.

A pipe is a shared memory buffer that base preallocates in full, though,
so a uniformly larger pipe makes every small response measurably slower
for the sake of the large ones. Instead, where the body size is known up
front, size the pipe to the body with the same caps upstream uses: archive
entries (file-like) up to the 2 MB file:// size, string/buffer responses
and any protocol response that declares a Content-Length up to the
512 KB default. Streams of unknown length keep mojo's default. Small
responses keep exactly the pipe they had; a 16 MB archive entry reaches
the renderer in 8 slices instead of 256, a 16 MB protocol body with a
known length in 32.

* perf: remember module stat results for paths inside an archive

Module resolution calls internalModuleStat() thousands of times while an
app loads from app.asar, and most of those repeat a path it already asked
about (parent node_modules directories, extension-less candidates):
loading a 1040-module tree issues 6357 calls for 2751 distinct paths, 5065
of them misses. Node's own stat cache only remembers hits and only within
one require() chain, so every repeat went back through the archive
lookup.

An archive's header never changes once it is open, so keep the answers
derived from it in a Map keyed by the path (bounded, cleared when it grows
past 16k entries). Answers that came from failing to open the archive are
not kept, so an archive that appears later is still picked up.

(cherry picked from commit 51d485b)
@MarshallOfSound
MarshallOfSound merged commit 911db2b into 42-x-y Aug 19, 2026
70 checks passed
@MarshallOfSound
MarshallOfSound deleted the bp/42-x-y/52923 branch August 19, 2026 15:31
@release-clerk

release-clerk Bot commented Aug 19, 2026

Copy link
Copy Markdown

Release Notes Persisted

  • Fixed a stall of tens of milliseconds while creating the first BrowserWindow on Linux.
  • Improved the performance of file lookups inside ASAR archives and of large files served from them to the renderer.
  • Improved the performance of calls through contextBridge-exposed APIs.
  • Reduced the main-thread cost of sending large values through ipcRenderer, ipcMain handlers and webContents.send.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

42-x-y backport This is a backport PR semver/patch backwards-compatible bug fixes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants