Skip to content

perf(runtime): cheaper runtime and RuntimeState lookups - #2146

Merged
edusperoni merged 2 commits into
mainfrom
perf/runtime-lookup-fast-path
Nov 22, 2026
Merged

edusperoni merged 2 commits into
mainfrom
perf/runtime-lookup-fast-path

Conversation

@edusperoni

@edusperoni edusperoni commented Nov 21, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Makes the runtime lookups on the JS ↔ Java bridge cheaper: Runtime::GetRuntime and RuntimeState::For.

perf(runtime): inline the runtime lookups' fast paths

  • GetRuntime(v8::Isolate*) is now inline. Its fast path is the isolate data-slot read that TryGetRuntime already did inline. Only the locked setup-window map lookup and the throw stay out of line, in GetRuntimeSlow. Before this, every V8 callback that looks up its runtime paid a call for one load.
  • GetRuntime(int), used on every Java → JS call, is now inline in the same way: the calling thread's own runtime is a thread-local read.
  • s_current is now declared constinit. Without it, other translation units check the thread-local's init hook (_ZTH…, a GOT load and a branch) before __emutls_get_address.
  • GetRuntimeFromIsolateData had no callers left after perf(runtime): hot-path quick wins on the JNI bridge #2141, so it is removed.

perf(runtime): make RuntimeState lookups cheaper

  • Slot indices are now claimed while the library loads, through an inline variable template. Before, each For<T> call checked a function-local static's guard (__cxa_guard byte).
  • The slots are a fixed array of 32 raw pointers with a separate deleter array, instead of a std::vector<unique_ptr<void, deleter>>. A lookup of existing state is now an inlined index and null check. The vector data-pointer load, the size check and the disposed_ check are gone from the fast path. Going past 32 state types fails an NS_CHECK when the library loads, in every build type.
  • Creating state stays out of line. Clear() empties every slot before it destroys anything, then destroys in reverse index order. That keeps the semantics main has: from the start of teardown, For returns null, its own type included, and never recreates state.
  • New For<T>(Runtime*) overload, which skips the isolate data-slot read. It is used by GetCallbackMethodName, which runs on every Java → JS call from a Runtime member.

Each subsystem still declares its state struct in its own .cpp. Nothing lists the state types centrally.

Generated code (arm64, MetadataNode::GetMetadataNodeCache)

Fast path after the isolate data-slot read
main ldr state; cbz; bl RuntimeState::GetOrCreate<T>: out of line, with guard byte, disposed_ check, vector grow loop and bounds check
(a) vector + load-time index 13 instructions, inlined: ldr state; cbz; adrp/ldr index; ldrb disposed; tbnz; ldp begin,end; sub; cmp; b.hs; lsl; ldr slot; cbz
(b) fixed array (this PR) 6 instructions: ldr state; cbz; adrp/ldr index; ldr [state, index, lsl #3]; cbnz

The kSlotIndex<T> load is a direct adrp+ldr, not GOT-indirect. Since JNI TryGetRuntime(int) now inlines GetRuntime(int), it is just __emutls_get_address, a compare and a return. The shipped libNativeScript.so is the same size (24,528,560 bytes) on main and on this branch.

Options evaluated and not taken

  • (a) Load-time indices with the vector kept. This is the smaller change, but its fast path is 13 instructions to (b)'s 6, with one more dependent load (the vector's data pointer). On callback.noArgs, (b) ran 7-10 fewer instructions per op than (a) in both stat sessions (one on main before perf(runtime): hot-path quick wins on the JNI bridge #2141): −44.7 vs −37.6 here, against an A/A difference of 0.6. The wrapper row went the other way (−35.9 vs −45.2), but its count swings with GC: in the earlier session it moved by about 800 instructions/op between identical runs.
  • Holding RuntimeState inline in Runtime instead of behind a unique_ptr. That would remove one more dependent load (runtime → state). But Runtime.h would need the full RuntimeState definition, while For needs the complete Runtime, so the headers would have to be split or reordered. The saving is one L1 load, at most once per call, on rows that take 700 ns or more. That is far below what this phone can resolve.
  • Compile-time slot indices. These need a central list of every state type, which is exactly what RuntimeState exists to avoid. All they would remove is the adrp/ldr of the index, which is off the critical path: it issues in parallel with the state-pointer load.

Measurements

Samsung SM-G780G (Android 13), optimized release APKs (-Poptimized -Prelease -Pabis=arm64-v8a), #2092 harness. base is main at 56c7b0b, and base2 is the same APK under a second label, as the A/A pair. Every label was reinstalled and speed-compiled every round, the first launch after the install was discarded, and only the relaunch was measured. There were six rounds with the order rotated. Ratios are per-round label/base; the table shows the median, with the min..max range in parentheses.

Time (ns/op, median of rounds)

row base A/A base2/base commit 1 only this PR this PR / base
static.noop() 89.2 0.998 (0.99..1.01) 0.979 85.8 0.966 (0.95..0.97)
static.add(int,int) 145.0 1.026 (0.97..1.04) 0.996 141.2 0.974 (0.96..0.98)
instance.noop() 228.4 1.003 (0.99..1.01) 0.997 228.2 0.999 (0.99..1.01)
field.get int 257.0 1.001 (1.00..1.00) 0.986 252.2 0.981 (0.98..0.99)
static field get int [small class] 101.0 1.002 (0.99..1.01) 0.942 97.6 0.967 (0.95..0.99)
static field get final int [android.R.id] 12.3 1.000 (0.93..1.07) 1.000 12.4 1.000 (0.93..1.11)
array get int[i] 351.0 0.992 (0.98..1.00) 0.986 345.7 0.984 (0.97..1.00)
overload static Math.max(int,int) 640.6 1.000 (1.00..1.01) 0.992 639.9 0.997 (0.99..1.01)
overload instance sb.append(int) 810.0 1.005 (1.00..1.02) 0.989 797.3 0.987 (0.97..1.00)
new Object.extend({})() 6229.8 0.987 (0.94..1.05) 0.981 6079.4 0.970 (0.95..1.00)
lifecycle new Object.extend({})() [alloc, kept alive] 6498.1 0.995 (0.91..1.08) 0.973 6268.2 0.965 (0.92..0.99)
lifecycle new Object.extend({})() [release: V8 gc] 588.4 1.018 (0.99..1.07) 1.018 601.3 1.017 (0.99..1.11)
lifecycle new Object.extend({})() [release: Java gc] 1125.6 1.000 (0.98..1.02) 1.002 1126.3 1.002 (0.99..1.02)
static.newObjectInJava() [new wrapper] 1033.3 1.005 (0.92..1.16) 0.934 965.5 0.937 (0.79..1.16)
new java.lang.Object() 1973.4 0.853 (0.66..1.86) 0.930 1542.8 0.757 (0.58..1.25)
lifecycle new java.lang.Object() [alloc, kept alive] 3329.7 0.867 (0.60..2.00) 0.970 2525.8 0.701 (0.56..1.45)
lifecycle new java.lang.Object() [release: V8 gc] 453.0 1.003 (0.97..1.02) 1.031 456.0 1.004 (0.99..1.11)
lifecycle new java.lang.Object() [release: Java gc] 1109.6 0.997 (0.98..1.01) 1.013 1119.6 1.010 (0.99..1.03)
new Iterator({remove}) [default override] 10926.0 0.991 (0.79..1.15) 1.029 10494.2 0.939 (0.87..1.05)
static.newInstance(extended class) [Java-created] 13095.5 0.943 (0.78..1.25) 0.911 11238.7 0.880 (0.83..1.01)
callback.noArgs() 1924.2 1.001 (0.32..1.14) 0.962 718.8 0.903 (0.36..1.01)
callback.oneObject(Object) 2863.2 0.991 (0.91..1.03) 0.965 2788.2 1.003 (0.91..1.02)

All 22 rows the run measured are listed. Wall-clock times can't support any claim about the object-creation, GC-release and callback rows: their A/A ranges span 10-100%, so the large ratios on new java.lang.Object() and its lifecycle row are noise, not a result. On this phone callback.noArgs() is bimodal per launch (about 730 or about 1950 ns), and its twoInts reference doesn't track it. The instruction counts below cover those paths.

simpleperf stat on the JS thread (two-scale difference, so per op of the row; instructions:u and cpu-cycles:u, no multiplexing)

row base instr A/A commit 1 only (a) vector this PR base cycles A/A commit 1 only this PR
static.add(int,int) 1148.5 +4.6 −14.6 −14.4 −14.4 295.9 +3.3 −1.9 −7.9
field.get int 1297.3 +1.8 −12.2 −12.3 −11.3 445.8 −0.8 −5.7 −7.6
callback.noArgs() (+ twoInts ref) 3725.7 −0.6 −21.7 −37.6 −44.7 noisy (A/A −332)
static.newObjectInJava() [new wrapper] 2207.4 +4.7 −14.3 −45.2 −35.9 noisy (A/A −58)

Commit 1 accounts for the per-call GetRuntime savings on every JS → Java row. Commit 2 adds about 23 instructions/op on Java → JS callbacks (CallbackMethodNames) and about 22 on wrapper creation (MetadataNodeCache), the two paths that call RuntimeState::For once per op. On main, a plain JS → Java call does not call RuntimeState::For.

No row is slower than base beyond the A/A noise. With commit 1 alone, lifecycle new java.lang.Object() [release: V8 gc] reads 1.031 against A/A 1.003, and [release: Java gc] reads 1.013 against 0.997. These are GC-release rows whose ranges overlap the A/A ones, and the full PR is back at A/A on both.

Related Pull Requests

Does your pull request have unit tests?

No new specs: the behavior is unchanged. The full suite passes on an API 36.1 arm64 emulator (1788 specs, 0 failures). Teardown semantics are the existing ones: For returns null once Clear has started, and never recreates state.

Summary by CodeRabbit

  • Refactor
    • Runtime lookups now use a faster path when the runtime is already available on the current thread or through its isolate.
    • Runtime state storage now has a fixed capacity, and cleanup clears stored entries before releasing their values.
    • Runtime state can be accessed directly from a runtime as well as from an isolate.

@coderabbitai

coderabbitai Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Explain Change →

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 20 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used all 4 included reviews currently available.

Learn how review limits work.

Review configuration:

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 7e43b8d and 5a634ee.

Files selected for processing: 4

  • test-app/runtime/src/main/cpp/Runtime.cpp
  • test-app/runtime/src/main/cpp/Runtime.h
  • test-app/runtime/src/main/cpp/RuntimeState.cpp
  • test-app/runtime/src/main/cpp/RuntimeState.h

No actionable comments were generated in the recent review.

Walkthrough

Runtime lookup methods now separate fast paths from slow lookups. RuntimeState now stores state objects in fixed-capacity arrays and supports runtime-based access. Callback method-name caching uses the current Runtime as its state key.

Changes: Runtime lookup and state

Layer / File(s) Summary
Fixed-slot RuntimeState lifecycle and access
test-app/runtime/src/main/cpp/RuntimeState.h, test-app/runtime/src/main/cpp/RuntimeState.cpp
RuntimeState replaces vector-backed storage with fixed arrays for up to 32 state types. It adds access through Runtime*. Clear nulls all slots before invoking non-null deleters in reverse slot order.
Runtime lookup dispatch
test-app/runtime/src/main/cpp/Runtime.h, test-app/runtime/src/main/cpp/Runtime.cpp
The runtime-ID and isolate lookup methods use fast paths before calling GetRuntimeSlow. GetRuntimeFromIsolateData is removed. The s_current thread-local definition and declaration are marked constinit.
Callback cache keyed by Runtime
test-app/runtime/src/main/cpp/Runtime.cpp
Callback method-name lookup retrieves its cache from RuntimeState using the current Runtime.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Refactor

Suggested reviewers: vmutafov, nathanwalker

Merge Risk: Minimal · previous review 7e43b

This change speeds up runtime and state lookups on the JS-to-Java bridge without altering behavior. No concrete defect was found in the lookup fast paths, the fixed-slot state storage, or its teardown ordering. It looks safe to merge.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title "perf(runtime): cheaper runtime and RuntimeState lookups" matches the main change. The PR inlines the fast paths of Runtime::GetRuntime and makes RuntimeState slot lookup an inlined array in…
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.
Full details: Title check

Explanation

The title "perf(runtime): cheaper runtime and RuntimeState lookups" matches the main change. The PR inlines the fast paths of Runtime::GetRuntime and makes RuntimeState slot lookup an inlined array index with load-time slot indices. It is a short, single-sentence, conventional-commit title that names the primary change and the two areas it touches. The title does not list every detail, such as the removed GetRuntimeFromIsolateData helper or the new Clear() teardown behavior, which is acceptable.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 56c7b0b and 7e43b8d.

Files selected for processing: 4

  • test-app/runtime/src/main/cpp/Runtime.cpp
  • test-app/runtime/src/main/cpp/Runtime.h
  • test-app/runtime/src/main/cpp/RuntimeState.cpp
  • test-app/runtime/src/main/cpp/RuntimeState.h

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 2 remain after this review.

@edusperoni
edusperoni marked this pull request as ready for review November 22, 2026 21:15
Every V8 callback that looks up its runtime paid an out-of-line call for
what is a single isolate data-slot load, and every Java -> JS call did the
same for a thread-local read. Only the locked map lookups and the throws
stay out of line. GetRuntimeFromIsolateData had no callers left.
Slot indices are claimed while the library loads instead of behind a
function-local static's guard, and the slots are a fixed-size array, so a
lookup of existing state is an inlined index and null check: no vector
bounds check, and no separate disposed check, since teardown empties every
slot first. Creation stays out of line, and callers that already hold the
Runtime can skip the isolate data-slot read.
@edusperoni
edusperoni force-pushed the perf/runtime-lookup-fast-path branch from 7e43b8d to 5a634ee Compare November 22, 2026 21:22
@edusperoni
edusperoni merged commit f103fd0 into main Nov 22, 2026
11 checks passed
@edusperoni
edusperoni deleted the perf/runtime-lookup-fast-path branch November 22, 2026 21:41
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.

1 participant