Skip to content

[JSC] CodeCacheMap picks the entry to evict without walking the hash table - #676

Merged
Jarred-Sumner merged 2 commits into
mainfrom
robobun/a3b642d8/code-cache-prune-random
Sep 21, 2026
Merged

Jarred-Sumner merged 2 commits into
mainfrom
robobun/a3b642d8/code-cache-prune-random

Conversation

@robobun

@robobun robobun commented Sep 16, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

  • Once the code cache holds 2000 entries, each new program, ES module, eval or new Function source costs a walk over much of its hash table. In Bun, new vm.Script("1 + " + i) has 30% of its samples in CodeCacheMap::pruneSlowCase, and 10000 small modules load 10% slower.
  • pruneSlowCase (runtime/CodeCache.cpp) evicts m_map.begin(), which skips every empty and deleted bucket before the first entry. Evicting the first entry each time empties the front of the table: one eviction walks about 2300 of the 8192 buckets.
  • The victim is the entry with the lowest bucket index, so a source that is used again and again is a cache hit only about half of the time with 300 new sources between two uses.

Fix

  • Evict the least recently used of five entries from m_map.random() (6 probes or fewer each). Each entry already records its last use in SourceCodeValue::age.
  • Bun with the preview build: a new vm.Script source 6.1 us to 4.2 us, 10000 modules 191 ms to 173 ms. jsc: eval of a new source 5.1 us to 3.4 us, and the reused sources above always hit.
  • Verified: two new microbenchmarks (global-code-many-distinct-sources.js 189 ms to 155 ms, global-code-reused-among-distinct-sources.js 385 ms to 167 ms) and 123 eval and Function constructor stress tests with identical output on both builds.

Background

  • The code cache maps a source (SourceCodeKey) to its unlinked bytecode, so a VM parses the same text once.
  • prune() runs on every lookup and insert. It evicts while the cache holds more bytes than its capacity, or 2000 entries or more. With small sources every insert evicts one entry.
  • HashTable::begin() steps over empty and deleted buckets one at a time.
Notes

Bun with this change. Two release builds of Bun c6b7fcb5bb (linux x64), one with stock WebKit c281568 and one with the preview build of this PR's first head (autobuild-preview-pr-676-48438b04, the same two commits before the rebase). The host was loaded, so the numbers are minimums.

New sources, ns per call, mean of batches 5 to 12 of 1000 sources each (the cache is full from batch 3), minimum of 12 interleaved runs:

stock this PR
new vm.Script("1 + " + i) 6149 4195
(0, eval)("1 + " + i) 6581 4633
new Function("return 1 + " + i) 6116 3681

Module loading. Every ES module source is one entry of the same cache (getUnlinkedModuleProgramCodeBlock), so a program pays the walk for each module after the 2000th. N files that each contain export const v = <i>; and an entry file with one import line per file, wall time of bun entry.js in ms, minimum and first quartile of 60 interleaved runs:

N stock this PR stock, BUN_JSC_useCodeCache=0
5000 77.5 / 115.7 70.7 / 105.1 68.8 / 105.4
10000 191.3 / 241.6 172.8 / 221.1 154.5 / 212.6

On a quieter host, stock only, minimum of 15 runs: 66.9 ms with the cache and 61.8 ms without it at N = 5000, 152.9 ms and 134.7 ms at N = 10000, and no difference at N = 1000 and 2000. A separate count of instructions on one pinned core puts pruneSlowCase at 0.5% of the load at N = 2000, 7.2% at N = 5000 and 10.7% at N = 10000, on every Bun release back to 1.3.14.

Three builds of jsc with the same flags (release, linux x64): the base, m_map.random() alone (the first commit), and the least recently used of five random entries (the second commit).

Cost of a new source, ns per call for each batch of 1000 new sources, minimum of 12 interleaved runs. The cache reaches 2000 entries in the second batch. The script warms the loop with cached sources first.

ns per call 1 2 3 4 5 6 7 8 9 10 11 12
eval, base 2969 2954 4090 4687 5499 5458 5618 5304 4847 4772 4508 4434
eval, random 3042 3007 3281 2954 3323 3068 2996 3055 3220 3250 3021 3021
eval, oldest of 5 3439 3879 4175 4609 3837 3309 3145 3355 3374 3564 3210 3161
new Function, base 2486 2352 3479 4110 4848 4627 4856 4654 4321 4180 3843 3848
new Function, random 2518 2400 2614 2370 2702 2292 2339 2473 2508 2576 2313 2350
new Function, oldest of 5 2546 2377 2825 2541 2819 2432 2523 2634 2692 2861 2480 2468

Mean of batches 5 to 12: eval 5055, 3119, 3369. new Function 4397, 2444, 2613. The four more samples cost about 200 ns per new source.

var globalEval = eval;
var which = arguments[0] || "eval";
var fn = which === "eval" ? function (i) { return globalEval("1 + " + i); } : function (i) { return new Function("return 1 + " + i); };
for (var w = 0; w < 3000; ++w)
    fn(w % 10);
var out = [];
var next = 100;
for (var b = 0; b < 12; ++b) {
    var t = preciseTime();
    for (var i = 0; i < 1000; ++i)
        fn(next++);
    out.push(Math.round((preciseTime() - t) * 1e9 / 1000));
}
print(JSON.stringify(out));

Hit rate of reused sources. 100 sources of about 20 KB are evaluated in a loop, with N new one-line sources between two rounds, after 4000 new sources filled the cache. A parse of one of the 100 costs about 1.3 ms and a hit about 0.35 ms, so the time of a round gives the hit rate.

N base random oldest of 5
50 45 to 48% 100% 100%
300 38 to 59% 86 to 93% 100%
1000 29 to 32% 43 to 50% 98 to 100%
3000 0 to 32% 0 to 15% 0 to 17%

The ranges are over 2 to 4 runs on a loaded host. The time of one reused eval is steadier than the rate: at N = 300 it is 522 us on the base, 250 to 266 us with random() and 177 to 181 us with the oldest of five, where a hit costs about 190 us.

A simulation of the table with small sources gives the same order: begin() keeps 14% of a reused set whatever N is, random() keeps e^(-N/2000) of it, the oldest of five keeps all of it up to N = 650 and 96% at N = 1000. Past N = 2000, the size of the cache, a least recently used policy keeps nothing. begin() keeps the few entries whose buckets are high, by chance. Those uses are less than 1 in 2000 of the compiles.

Microbenchmarks, 11 interleaved runs, minimum and median in ms:

base random oldest of 5
global-code-many-distinct-sources.js 189 / 226 162 / 213 155 / 192
global-code-reused-among-distinct-sources.js 385 / 465 214 / 263 167 / 243

Where the 2300 buckets come from:

  • The table grows to 4096 buckets for 2000 keys. The first evictions add deleted buckets, keyCount + deletedCount reaches half the table, and expand() doubles it to 8192 because mustRehashInPlace() (keyCount * 6 < tableSize * 2) is false at 4096. At 8192 it is true, so from then on every expansion is a rehash in place, and shouldShrink() (keyCount * 6 < tableSize) is false. The table stays at 8192.
  • A rehash in place puts an entry at hash & mask again. The region in front of the first entry stays empty across rehashes.
  • A simulation of this table (open addressing, the same probe sequence, deleted buckets, the same expand and shrink rules) with 2000 keys, one random insert and one begin() eviction per step, settles at 2300 buckets walked per eviction (2279 to 2438 over windows of 2000 evictions, after the first 10000 steps).
  • sizeof(CodeCacheMap::MapType::KeyValuePairType) is 56 (checked with a static_assert in this build).
  • The measured difference agrees: about 2 us per new source for about 2300 cache lines.

HashTable::random() probes random buckets until it finds an entry. The table shrinks below a load of 1/6, so it needs 6 probes or fewer on average.

age is m_age at the last use of the entry, and m_age only grows, so the lowest age is the least recently used entry. Five is the sample size Redis uses for the same approximation of LRU.

The first microbenchmark sums the results and checks the sum. Before #346 landed it failed on every build: two sources of equal length whose 24-bit string hashes collide got the code of the first one. The branch is rebased on a main that has #346, and the check passes on the stock jsc of that main.

Upstream WebKit has the same pruneSlowCase.

The Bun side of the same report (option parsing and the origin URL in node:vm) is a separate PR in oven-sh/bun.

@coderabbitai

coderabbitai Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Essentials

Run ID: 865e9233-f46a-494b-ad4a-08ba3ff24235

📥 Commits

Reviewing files that changed from the base of the PR and between c281568 and 48438b0.

📒 Files selected for processing (4)
  • JSTests/microbenchmarks/global-code-many-distinct-sources.js
  • JSTests/microbenchmarks/global-code-reused-among-distinct-sources.js
  • Source/JavaScriptCore/runtime/CodeCache.cpp
  • Source/JavaScriptCore/runtime/CodeCache.h

Included review availability: Your plan provides up to 5 included reviews per hour; 1 remains after this review.


Walkthrough

The change updates CodeCacheMap eviction to sample five entries and select the oldest sampled entry. Two microbenchmarks exercise distinct and reused global evaluation sources.

Changes

Code cache eviction

Layer / File(s) Summary
Sampled cache eviction
Source/JavaScriptCore/runtime/CodeCache.h, Source/JavaScriptCore/runtime/CodeCache.cpp
CodeCacheMap defines a five-entry sampling size. pruneSlowCase() selects the oldest entry from the sampled entries.
Evaluation cache benchmarks
JSTests/microbenchmarks/global-code-many-distinct-sources.js, JSTests/microbenchmarks/global-code-reused-among-distinct-sources.js
The benchmarks exercise distinct evaluations and repeated reusable evaluations mixed with unique expressions. Each benchmark validates the expected result count.

Priority: ⬇️ Low

Merge Risk: ⚪ Minimal · up to 48438

No confirmed merge-blocking issue remains in the available evidence.

🚥 Pre-merge checks | ✅ 3 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description gives a detailed problem statement, implementation rationale, performance data, and validation results. However, it does not follow the repository template because it lacks a bug title… Add the associated Bugzilla title and link, include the required review-status line, and add the template-formatted list of changed paths and relevant functions or classes.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies the main change: CodeCacheMap selects eviction entries without walking the hash table.
Full details: Description check

Explanation

The description gives a detailed problem statement, implementation rationale, performance data, and validation results. However, it does not follow the repository template because it lacks a bug title and Bugzilla link, the required “Reviewed by NOBODY (OOPS!).” line, and a structured list of changed files and symbols.

  • Fix all pre-merge checks with AI

Warning

Git: CodeRabbit could not clone the repository, so clone-backed analysis was skipped and this review may be incomplete. Verify repository clone access, such as SSH credentials, before requesting another full review. If clone access is intentionally unavailable, use path_filters to narrow the review scope.


Comment @coderabbitai help to get the list of available commands.

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

Beyond the inline finding, I also checked the empty-map case in pruneSlowCase: HashTable::random() returns end() when keyCount() is 0, exactly as begin() did, so the loop's dereference is no more exposed than before; the m_size and remove(it) bookkeeping is unchanged. The new microbenchmark's runtime under debug/ASan was also looked at and ruled out: JSTests/microbenchmarks is a benchmark collection whose existing entries routinely exceed the 200 ms stress-test rule, and the asan lanes are not tested in CI.

Extended reasoning...

A finding on the eviction-policy change was already posted inline, so this note only records what else was examined. random() in Source/WTF/wtf/HashTable.h:454 guards isEmpty() and returns end(), matching begin()'s behavior on an empty table, so the change does not introduce a new null-iterator path in the while loop at Source/JavaScriptCore/runtime/CodeCache.cpp:50; the loop body (writeCodeBlock, m_size -= key.length(), remove(it)) is untouched. The new file JSTests/microbenchmarks/global-code-many-distinct-sources.js is a fork-only addition to the microbenchmark collection (not a changed upstream expectation, so BUN-TEST-DIFFERENCES.md is not implicated), and its ~190 ms release runtime is in line with that collection.

@github-actions

github-actions Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

Preview build of e6da8f0: autobuild-preview-pr-676-e6da8f0f

@robobun robobun changed the title [JSC] CodeCacheMap evicts an entry without walking the hash table [JSC] CodeCacheMap picks the entry to evict without walking the hash table Sep 16, 2026

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I re-reviewed after 48438b0 (LRU-of-5 sampling) and found no bugs; the follow-up addresses the hot-set eviction concern from my earlier inline comment. Since this changes a core JSC runtime eviction policy under /Source/JavaScriptCore (CODEOWNERS-covered), a human look is still worthwhile.

What was reviewed:

  • The sampling loop in pruneSlowCase dereferences random() without an end() check: safe, because m_capacity is never negative (only clamped up to m_minCapacity >= 0) so m_size > m_capacity cannot hold with an empty map, and !canPruneQuickly() needs 2000 entries.
  • Age comparison direction: value.age is m_age at last use, so the smallest sample is the least recently used; consistent with findCacheAndUpdateAge/addCache.
  • The PR description and its measurements still describe the single m_map.random() version ("the victim was already arbitrary"); worth updating to match the LRU-of-5 code before merge.
Extended reasoning...

Overview

The diff touches Source/JavaScriptCore/runtime/CodeCache.cpp (CodeCacheMap::pruneSlowCase), CodeCache.h (new evictionSampleSize = 5 constant), and adds two microbenchmarks under JSTests/microbenchmarks/. The first commit replaced m_map.begin() with m_map.random() as the eviction victim; the second commit, pushed after my prior inline comment, samples five random entries and evicts the one with the smallest value.age. Everything else in the loop (writeCodeBlock, m_size accounting, m_map.remove(it), the loop condition) is unchanged.

Security risks

None identified. The change only affects which cached unlinked code block is dropped from an in-memory, per-VM cache; it does not change lookup semantics, key comparison, or what code is returned for a source. WTF::HashTable::random() returns end() only for an empty table, and I verified the loop condition cannot be true on an empty map (m_capacity starts at 0, is only ever decreased with a clamp to m_minCapacity, which is itself clamped to >= 0; m_size is 0 when the map is empty), so the unchecked dereference is sound. The pre-existing code had the same implicit reliance on non-emptiness via begin().

Level of scrutiny

Moderate. The code change is small (about ten lines) and easy to reason about, but it alters the eviction policy of a cache that every program, indirect eval, new Function and vm.Script in Bun goes through, and the path is under /Source/JavaScriptCore and /JSTests, both covered by CODEOWNERS. That rules out an automated approval even though I found nothing wrong. The interaction with the adaptive m_capacity heuristic in findCacheAndUpdateAge is benign: the heuristic sizes the cache from the age of hits and never depended on which entry was evicted, and approximate-LRU only makes hits younger on average.

Other factors

The PR description and the measurement table were written for the first commit and describe evicting a single random entry with the argument that the victim was already arbitrary; the merged code is LRU-of-5, and the second microbenchmark (reuse workload) was presumably added to exercise exactly that. A human should confirm the description is updated so the rationale in history matches the code. The microbenchmarks are performance tests, not stress tests, so the 200 ms guidance in JSTests/README.md for JSTests/stress does not strictly apply; they are new files rather than modified upstream tests, so no BUN-TEST-DIFFERENCES.md entry is required. The hunt exited on dry_streak with no findings.

pruneSlowCase() evicted m_map.begin(). HashTable::begin() skips every empty
and deleted bucket in front of the first entry, and evicting the first entry
each time empties the front of the table. Once the cache holds 2000 entries,
every source it has not seen evicts one entry, and each eviction walked about
2300 of the table's 8192 buckets. Evict m_map.random(), which needs a few
probes.
A source that is used again and again should stay in the cache while
sources that are used once pass through it. Each entry already records
when it was last used (SourceCodeValue::age). Look at five random entries
and evict the one with the lowest age.
@robobun
robobun force-pushed the robobun/a3b642d8/code-cache-prune-random branch from 48438b0 to e6da8f0 Compare September 17, 2026 21:06

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I reviewed the updated PR and found no bugs; the second commit's age-based pick from the five random samples addresses the hit-rate concern from my earlier inline comment. Since Source/JavaScriptCore and JSTests are CODEOWNERS paths (jsc-reviewers), a human look is still worthwhile before merging.

What was reviewed:

  • The eviction loop cannot run on an empty map: m_size is 0 when the map is empty and m_capacity >= m_minCapacity >= 0, so m_size > m_capacity || !canPruneQuickly() is false there and random() never returns end() inside the loop.
  • SourceCodeValue::age is the monotonically increasing int64_t m_age at the entry's last add or hit, so the lowest of the samples is the least recently used; no wrap in practice.
  • HashTable::random() probes random buckets until a live one, so its cost is bounded by the table's load (kept at or above 1/6 by shrinking), not by the empty prefix begin() walked; repeated picks among the five samples are harmless.
  • The two new microbenchmarks are new files, so no BUN-TEST-DIFFERENCES.md entry is required; the first checks a summed result and the second checks types only, which sidesteps the known SourceCodeKey::operator== hash-collision gap.
Extended reasoning...

Overview

The PR changes one function, CodeCacheMap::pruneSlowCase() in /home/claude/webkit/Source/JavaScriptCore/runtime/CodeCache.cpp, and adds one constant, evictionSampleSize = 5, to /home/claude/webkit/Source/JavaScriptCore/runtime/CodeCache.h. Instead of evicting m_map.begin() on every iteration of the prune loop, it draws five iterators via HashMap::random() and evicts the one with the smallest value.age. Two new microbenchmarks in /home/claude/webkit/JSTests/microbenchmarks/ exercise the all-miss case (every eval/Function source is new, so the 2000-entry cache evicts per insert) and the reuse case (50 large sources re-evaluated with 300 fresh sources between rounds). The second commit (age-based selection) is what my earlier inline comment on the first version asked for, and the code now matches that request.

Security risks

None specific to this change. The code cache maps a source key to unlinked bytecode within one VM; the eviction policy affects only which cached entries survive, not what code is returned for a key. random() uses weakRandomNumber, which is fine here since it is only a load-balancing choice with no adversarial surface. The pre-existing key-collision issue (SourceCodeKey::operator== not comparing text under USE(BUN_JSC_ADDITIONS), tracked in BUN-TEST-DIFFERENCES.md) is unchanged by this PR; the benchmarks were written to avoid tripping over it.

Level of scrutiny

Moderate. The C++ change is about ten lines and self-contained, and I verified the three things that could go wrong: the loop cannot execute on an empty map (m_size is the sum of live key lengths and m_capacity is clamped to a non-negative m_minCapacity, so the guard is false when empty, which also holds for the pre-existing begin() version), age is a monotonic int64_t stamped on add and on hit so "lowest age" is LRU, and HashTable::random() returns end() only for an empty table and otherwise probes until it hits a live bucket, so its cost tracks table load rather than the empty prefix. However, this is a hot path in the JS engine (every eval, new Function, vm.Script and program load goes through prune()), the paths are covered by CODEOWNERS (/Source/JavaScriptCore and /JSTests -> jsc-reviewers), and the fork diverges from upstream WebKit here, so a maintainer should still confirm the policy choice and the performance claims are acceptable.

Other factors

The bug hunt exited on dry_streak with no findings. The new microbenchmarks fail by throwing and check results rather than printing. They hard-code iteration counts rather than using testLoopCount, which is conventional for microbenchmarks/; reported release runtimes (155 ms and 167 ms) are in line with other files in that directory, though debug/ASan configurations will be slower, as with any microbenchmark. The earlier inline thread was resolved by the author, but the second commit's diff shows the age comparison was actually added, so the objection is addressed on the code, not just on the metadata. I deferred rather than approved solely because of the CODEOWNERS coverage and the engine-hot-path nature of the change.

@Jarred-Sumner
Jarred-Sumner merged commit 564ac2a into main Sep 21, 2026
49 checks passed
Jarred-Sumner pushed a commit to oven-sh/bun that referenced this pull request Sep 24, 2026
…URL on every call (#42955)

### Problem
- Since 1.4.0 (#38381) `vm.runInContext()` and `vm.runInNewContext()`
pass `{ ...options }` to `Script`, as Node does, so the native option
parser runs on every call: 2.5 us on main, 1.4 us on 1.3.14.
- The parser makes each option name with `Identifier::fromString(vm,
"lineOffset"_s)` (`NodeVM.cpp`, `NodeVMScript.cpp`): 15 atom table
lookups per call, plus an allocation, an insert and a removal for each
name no live code holds (`contextName`, `displayErrors`). That is 27% of
a profile of the call.
- Each `Script` and `vm.compileFunction()` call parses its filename into
a `file:` URL. The default `evalmachine.<anonymous>` takes the slow
percent-encoding path: 9% of the profile.

### Fix
- `NodeVMOptionNames` atomizes each option name on first use and keeps
it per VM in `JSVMClientData`, as `HTTPHeaderIdentifiers` does for
header names. A VM that reads no option pays nothing.
- `NodeVM::sourceOriginURL()` keeps the last filename and its URL per
VM, as `DOMURLBaseCache` does for `new URL(input, base)`. No property
read, read order or URL changes.
- Release builds, ns per call: `vm.runInContext(src, ctx)` 2484 to 1702,
`new vm.Script(src, {})` 902 to 394, `new vm.Script(src)` 374 to 272. No
measured case is slower.
- Verified: 5 new tests in `test/js/node/vm/vm.test.ts` and a new source
lint, of which 3 fail without the fix. Also all of `test/js/node/vm/`
and the 98 Node `test-vm-*` files.

### Background
- An `Identifier` is an interned string. Property lookup compares
pointers, so a name must be in the thread's atom table.
`Identifier::fromString` finds or creates that entry on each call.
- A `SourceOrigin` is the URL that `import()` in the code resolves
against. node:vm makes it from `filename`.
- `JSVMClientData` is Bun's per-VM C++ state.

<details><summary>Notes</summary>

Self-reviewed: 2 concerns raised, 2 addressed. Both asked for text in
these notes: the cases of the benchmark this came from with the share
this PR takes back, and the order with #42627.

Where this came from: a benchmark of node:vm across Bun releases, not a
user report. There is no issue. It measured `new vm.Script(src)` at 477
ns on 1.3.14 and 4.16 us on 1.4.0, and `vm.runInContext(src, ctx)` at
1.50 us and 6.01 us. Its three cases with its own loop (the median of 7
rounds of 50000 calls), minimum of 5 processes for each binary, ns per
call. The host was slower during this run than during the runs below.

| | 1.3.14 | 1.4.2 | base | fix | Node v26.3.0 |
| --- | --- | --- | --- | --- | --- |
| `new vm.Script("1 + " + i)` | 587 | 6105 | 6157 | 6252 | 2906 |
| `vm.runInContext("x + 1", ctx)` | 2684 | 3472 | 4453 | 2711 | 2903 |
| `script.runInContext(ctx)` | 1829 | 2023 | 2047 | 1981 | 1271 |

```js
const hot = (fn, n) => {
  for (let i = 0; i < 20000 && i < n; i++) fn(i);
  const r = [];
  for (let k = 0; k < 7; k++) {
    const t = performance.now();
    for (let i = 0; i < n; i++) fn(i);
    r.push(((performance.now() - t) * 1e6) / n);
  }
  r.sort((a, b) => a - b);
  return Math.round(r[3]);
};
const vm = require("node:vm");
const ctx = vm.createContext({ x: 1 });
const once = new vm.Script("x + 1");
console.log({
  'new vm.Script("1 + " + i)': hot(i => new vm.Script("1 + " + i), 50000),
  'vm.runInContext("x + 1", ctx)': hot(() => vm.runInContext("x + 1", ctx), 50000),
  "script.runInContext(ctx)": hot(() => once.runInContext(ctx), 200000),
});
```

- `vm.runInContext("x + 1", ctx)`: this PR takes back most of the
regression, (base - fix) / (base - 1.3.14): 98% in this run and 74% in
the table below.
- `new vm.Script("1 + " + i)`: this PR takes back nothing. Every source
is new, so the cost is the compile and the code cache.

What this PR does not change: the cost of `new vm.Script()` for a source
the VM has not seen.
- 1.3.14 did not parse in the constructor at all. It threw no
`SyntaxError` until the script ran. Since 1.4.0 the constructor
compiles, as Node does (#38040), so most of that cost moved from the
first run to the constructor.
- About a third of the rest is JavaScriptCore's code cache. Once it
holds 2000 entries, each new source evicts `m_map.begin()`, which walks
a large part of the hash table (`CodeCacheMap::pruneSlowCase`). The
per-call cost of `new vm.Script("1 + " + i)` goes from 2.5 us to 5 us at
the 2000th source. Indirect `eval` and `new Function` with new sources
pay the same. That fix is oven-sh/WebKit#676.

How the time was measured:
- `base` is a `bun run build:release` build of c6b7fcb and `fix` is
the same build of this branch, same machine and compiler. The two
commits between them touch only `node:url` and `node:util`.
- Each case runs 2000 calls per round, 60 interleaved rounds per
process, 5 processes per build, alternating builds (100 calls and 15
rounds for the three context cases). The number is the minimum. The host
was loaded, so only the minimum is stable. 1.3.14, 1.4.2 and Node
v26.3.0 are the official binaries, for reference.

| ns per call | base | fix |
| --- | --- | --- |
| `new vm.Script(src)` | 374 | 272 |
| `new vm.Script(src, {})` | 902 | 394 |
| `new vm.Script(src, { filename })` | 802 | 374 |
| `new vm.Script(src, { filename })`, two filenames in turn | 795 | 535
|
| `script.runInContext(ctx)` | 1056 | 1025 |
| `script.runInContext(ctx, {})` | 1362 | 1079 |
| `script.runInThisContext()` | 875 | 861 |
| `script.runInThisContext({})` | 1211 | 978 |
| `vm.runInContext(src, ctx)` | 2484 | 1702 |
| `vm.runInThisContext(src)` | 1407 | 1155 |
| `vm.compileFunction(src)` | 1718 | 1655 |
| `vm.compileFunction(src, [], {})` | 2144 | 1710 |
| `vm.createContext({})` | 81789 | 82581 |
| `vm.createContext({}, { name })` | 81894 | 81689 |
| `vm.runInNewContext(src, {})` | 172888 | 172122 |

The three context rows differ by 1% or less, which is the noise of this
host.

An earlier run with the official 1.3.14 and 1.4.2 binaries and Node
v26.3.0 next to the two builds, 4 processes each (`fix` there is the
first commit of this PR):

| ns per call | 1.3.14 | 1.4.2 | base | fix | node |
| --- | --- | --- | --- | --- | --- |
| `new vm.Script(src)` | 293 | 351 | 381 | 269 | 1221 |
| `new vm.Script(src, {})` | 1093 | 868 | 896 | 400 | 1192 |
| `new vm.Script(src, { filename })` | 864 | 799 | 789 | 395 | 1189 |
| `script.runInContext(ctx, {})` | 1470 | 1387 | 1357 | 1158 | 792 |
| `script.runInThisContext({})` | 1258 | 1267 | 1313 | 950 | 456 |
| `vm.runInContext(src, ctx)` | 1429 | 2438 | 2532 | 1736 | 2388 |
| `vm.runInThisContext(src)` | 1220 | 1350 | 1440 | 1232 | 1952 |
| `vm.compileFunction(src, [], {})` | 2557 | 2226 | 2151 | 1771 | 939 |
| `vm.createContext({})` | 86206 | 77758 | 76888 | 74642 | 301548 |
| `vm.runInNewContext(src, {})` | 182839 | 164942 | 173888 | 167683 |
312421 |

The case with two filenames in turn misses the URL cache on every call.
A miss adds one string comparison and two assignments to the parse.

Why some names cost more than others: `breakOnSigint`, `cachedData`,
`columnOffset`, `importModuleDynamically`, `lineOffset` and `timeout`
appear in `src/js/node/vm.ts`, so their atoms are usually alive and the
old code paid a hash and a table lookup for each. `contextName`,
`contextOrigin`, `produceCachedData`, `displayErrors`, `parsingContext`
and `contextExtensions` appear nowhere else, so each lookup allocated
the atom, inserted it, and removed and freed it again.

Why not builtin names: an entry in `BunBuiltinNames.h` costs every VM an
atom, a private name and a registration at startup, whether it loads
node:vm or not. The lazy table costs 17 null pointers.

The URL parse itself: a 32 KB filename of `<` characters takes about 1
ms to make into a URL, about 30 ns per character. The percent-encoding
path of `WTF::URLParser` is slow, but a filename that needs it is rare
apart from the default name, so this PR does not touch the parser.

The tests:
- Two tests compile Scripts and functions whose filenames alternate
between two directories and `import("./dep.mjs")` from each. Each
compile finds the URL of the other filename in the cache, so a stale hit
resolves the wrong module. These pass with and without the fix.
- Two tests use a 16 KB filename of `<` characters, so that the URL
parse dominates a compile. Each compares two windows of four compiles,
best of three trials: two filenames in turn (every compile makes a URL)
against one filename again (none does). The assertion is `repeated <
alternating / 2`. The ratio is 0.90 to 0.96 on a release build of main,
0.004 to 0.02 on the debug ASAN build of this branch.
- One test compiles a Script whose filename is a slice of a 128 MB
string, in a child process with `BUN_JSC_useCodeCache=0`, and checks
that the string is gone after a collection. The cache keeps an isolated
copy of the filename for this reason. The test fails without the copy
(128 MB kept). It is skipped under ASAN, where freed memory stays in the
quarantine. With the code cache on, main keeps such a string too: the
cache entry holds the `SourceProvider`, and its `sourceURL` is the
sliced string.
- The option names change nothing observable except time, and the gap
(about 0.5 us in 2 us) is too small for a timing assertion that does not
flake. `test/internal/source-lints/node-vm-option-names.test.ts` checks
the source instead: no `getIfPropertyExists(...,
Identifier::fromString(...))` in `NodeVM.cpp` and `NodeVMScript.cpp`,
also when the call spans lines. It reports 20 lines on main.

`test/js/node/vm/script-leak.test.ts` times out on a debug build (10000
compiles of a 90 KB source take 21 s there). It does that without this
change too. It passes on the release build, before and after.

Order with #42627 (open): it deletes `validateTimeout` and rewrites
`RunningScriptOptions::fromJS`, three hunks that this PR edits. The one
that lands second needs a rebase.
- If #42627 lands first, this PR drops its `validateTimeout` edit and
converts the three reads that #42627 adds (`timeout`, `displayErrors`,
`breakOnSigint`) to `optionNames(vm)`. The run-method rows of the tables
then need a new measurement. The constructor rows do not.
- If this PR lands first, the new source lint fails on #42627 until it
converts those three reads. There is a note on #42627.

Found on the way and reported separately: `script.runInNewContext(obj)`
creates a new global even when `obj` is already a context, so
`vm.runInNewContext(code, obj)` pays for two contexts and misses the
`let` bindings that Node sees.

</details>

<!-- robobun:evidence:begin -->

---

**no test proof** · iteration 0 · platform-specific test(s) that do not
run on this machine, deferring to CI, which covers all platforms:
test/js/node/vm/vm.test.ts

<!-- robobun:evidence:end -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants