Skip to content

perf(runtime): hot-path quick wins on the JNI bridge - #2141

Merged
edusperoni merged 6 commits into
fix/nested-object-array-elementfrom
perf/hot-path-quick-wins
Nov 21, 2026
Merged

edusperoni merged 6 commits into
fix/nested-object-array-elementfrom
perf/hot-path-quick-wins

Conversation

@edusperoni

@edusperoni edusperoni commented Nov 21, 2026 •

Copy link
Copy Markdown
Collaborator

Description

A batch of small, mechanical cuts to per-call work on the JS ↔ Java bridge: heap allocations, string copies, thread-local reads, out-of-line trivial calls and lookups repeated within one call. No locks, copies or process-wide Isolate*-keyed state are added; the new per-isolate state goes through V8StringConstants and MetadataNodeCache like the existing keys.

Allocations and copies (perf(runtime): drop per-call copies and dead work on the call paths)

  • JsArgConverter::ConvertArg zero-filled a 1 KB error buffer for every argument; it is now only NUL-terminated (every reader uses the C string).
  • The object/cast branch of ConvertArg created an unused JEnv and looked up the runtime for every object argument. The object manager is now resolved once per converter, and only for a plain object argument. The destructor skips its JEnv when no local refs were recorded.
  • instrumentation::Frame copied its name into a std::string, so every TNSPERF() frame heap-allocated for names longer than the SSO buffer, even with instrumentation off. These frames cover the class, extended-class and interface constructors and GetImplementationObject. Literal and __func__ names are now kept as pointers; dynamic names still own a copy.
  • The class, extended-class and interface constructor callbacks copied their class names on every new. They now pass the stored names by reference, and build the -defaults name only when it is needed.

TLS / isolate passing (perf(runtime): pass the isolate instead of reading it from TLS)

  • ArgConverter::ConvertToJavaString, NumericCasts::GetCastValue, MetadataNode::GetNodeFromHandle, the single-value JsArgToArrayConverter and the array element accessors now take the isolate from their callers instead of calling Isolate::GetCurrent() (emulated TLS below API 29).
  • CallJavaMethod looked the runtime up twice per call; it reuses the first lookup.
  • The instance field getter and setter looked up the runtime only to call the static ObjectManager::IsJsRuntimeObject.

Inlining (perf(runtime): inline trivial accessors used on every bridge call)

  • Runtime::GetIsolate/GetJavaRuntime/GetObjectManager/GetContext/GetId and JEnv's JNIEnv* conversion are now inline. The Runtime definitions sit after the class body, and its declarations are unchanged.
  • The MetadataEntry getters now inline only the check for an already-read value; reading the metadata stays out of line.

Return values and array elements (perf(runtime): cheaper JS -> Java return values and array element access)

  • Returning a JS value to Java used to cost a new jobject[1], a vector push, a DeleteGlobalRef(nullptr), and a NewLocalRef + DeleteLocalRef pair. The single-value converter now writes into an inline slot. ConvertJsValueToJavaObject takes the converted local ref over through ReleaseConvertedArg(); a borrowed (global/weak) ref is still copied into a new local, as before.
  • CreateJSInstanceNative no longer reads the instance's class name back through GetObjectClass + Class.getName(). Java already passes instance.getClass().getName(), which is the same name.
  • Java array element access copied the element signature and compared it against up to nine strings per access. It now switches on the element type.
  • Object elements go through ObjectManager::GetOrCreateJSWrapper, as method results and field reads do. This replaces GetOrCreateObjectId + GetClassName + a node lookup under the global node mutex.

Caching (perf(runtime): cache per-isolate keys and names used per access)

  • The implementation-object, supervalue and typemetadata private keys were rebuilt from strings, and resolved through V8's private-symbol registry, on every constructor call, super read and GetTypeMetadata. They are now created once per isolate in V8StringConstants. Private::ForApi on the same names returns the same symbols.
  • Kotlin property accessors copied the accessor's method name and created a new V8 string on every get and set. PropertyCallbackData now holds the internalized names. No spec reaches this path: the Kotlin property specs in tests/kotlin/properties/testPropertiesSupport.js are commented out. I re-enabled "Test Kotlin public properties should work" locally, and it fails here the same way it is expected to fail on main: the property reads as undefined, because no accessor is installed in the test app. The @get:JvmName spec calls methods, not properties.
  • CreateArrayWrapper took the global node mutex to look up java/lang/Object for every Java array it wrapped. Nodes are process-wide and never freed, so the pointer is resolved once.
  • MethodCallback decoded its External twice.

Not changed (from the audit list)

  • CanBeJavaString (6 compares per object-returning call) and the == "java/lang/String" per object field access: libc++ compares against a literal by length first, and the length is constant-folded. That leaves a handful of integer compares next to a JNI call, so precomputing them is not worth a new field on MetadataEntry/CacheMethodInfo/FieldCallbackData.

Benchmark rows added

test(bench): ... adds array get int[i], array set int[i], array get Object[i] and callback.objectReturn() -> Object to the #2092 harness. The base APK below includes them.

Measurements

Samsung SM-G780G (Android 13). Optimized release APKs (-Poptimized -Prelease -Pabis=arm64-v8a). The #2092 JNI harness ran with debug.ns.jnibench.

  • Labels: base = main plus the bench-row commit; new = this branch; base2 = the base APK under a second label, as an A/A control.
  • Procedure: labels interleaved base → new → base2 for 4 rounds. Every label was reinstalled and speed-compiled each round, and the first launch after each install was discarded; only the relaunch is measured. All 12 measured launches were in the same clock state (sentinel row 7.4–8.6 ns).
  • Columns: each cell is the median over launches of the per-launch median, in ns/op. "new vs base+base2" compares against the pooled 8 base launches.

The phone runs predate the rebase onto #2140 and #2143. Neither touches the measured paths, except array get Object[i]: #2143 changes only the branch for elements that are themselves arrays.

Rows below are beyond A/A noise: new's range does not overlap the pooled base range, and the change is more than twice the A/A delta.

row base base2 (A/A) new A/A new vs base+base2 new range base+base2 range
static.noop() 104.5 104.8 90.0 +0.3% -14.0% 89.8–90.4 104.2–105.1
static.add(int,int) 186.9 187.9 146.2 +0.5% -21.8% 145.2–146.5 186.4–188.8
static.addDouble(double,double) 230.7 233.8 198.1 +1.3% -14.3% 197.5–198.6 230.1–236.1
static.addLong(long,long) 195.3 194.9 155.5 -0.2% -20.2% 155.0–156.5 194.6–199.0
instance.noop() 238.1 238.6 228.9 +0.2% -3.9% 228.5–229.3 237.7–239.2
instance.getAlpha() [android.view.View] 245.3 244.2 234.9 -0.4% -4.0% 234.3–238.7 243.7–246.9
instance.getInt() 240.1 239.2 230.0 -0.4% -3.9% 228.5–231.1 238.7–241.5
instance.getChar() 253.7 252.1 242.1 -0.6% -4.1% 240.6–243.5 251.6–254.5
instance.getString() 425.6 424.8 416.4 -0.2% -2.0% 412.1–417.6 423.7–426.8
instance.self() [wrapped return] 414.7 419.8 404.9 +1.2% -2.5% 402.1–407.0 412.7–421.9
instance.getOther() [wrapped return] 412.9 416.8 403.4 +0.9% -2.3% 400.5–410.5 411.4–421.0
instance.takeObject(Object) 513.6 511.0 487.1 -0.5% -4.9% 483.9–492.8 509.9–519.3
instance.takeObjects(Object x3) 1078.7 1077.8 1013.5 -0.1% -6.0% 1008.8–1019.9 1074.0–1083.1
static.bufferCapacity(ArrayBuffer) 443.8 444.5 412.1 +0.2% -7.2% 401.0–412.3 439.1–456.5
static field get int [small class] 70.9 70.9 62.3 +0.1% -12.1% 62.1–62.5 70.4–71.2
static field get final int [small class] 70.8 70.9 62.0 +0.2% -12.5% 61.8–62.3 70.5–71.4
static field set int [small class] 73.5 73.3 65.2 -0.3% -11.0% 65.1–65.7 73.2–74.0
field.get int 162.6 162.1 153.1 -0.3% -5.7% 151.4–153.6 161.5–163.6
field.set int 162.0 162.3 152.8 +0.2% -5.8% 152.6–153.5 161.8–162.5
field.get Object 333.3 331.6 321.1 -0.5% -3.4% 318.9–324.6 327.3–336.9
field.get String 361.6 361.2 350.6 -0.1% -3.1% 350.1–352.0 358.9–364.0
array get int[i] 231.9 233.3 215.0 +0.6% -7.4% 214.2–215.9 230.9–236.5
array set int[i] 267.2 266.4 257.5 -0.3% -3.5% 256.7–258.7 266.1–269.7
array get Object[i] 408.1 405.3 363.6 -0.7% -10.7% 360.2–369.1 401.4–409.8
instance.self() [50k live wrappers] 417.0 422.4 406.8 +1.3% -2.8% 403.4–407.1 414.8–430.4
contention 1 thread(s), 3 new objects 8851.6 8924.8 8308.3 +0.8% -6.2% 8146.3–8474.8 8582.3–9704.9

Static calls get the most out of the 1 KB memset per argument and the inlined MetadataEntry getters. The array rows show the element-type switch and the GetOrCreateJSWrapper path.

Within noise:

  • The first-access rows: one sample per launch, with A/A up to ±20%.
  • Object creation and lifecycle rows.
  • instance.echo(String 1KB), which is bimodal in all three labels.
  • Contention rows other than the one above.
  • Callbacks: the harness cannot resolve them. Callback rows divided by the reference callback show A/A of 15–24%, and raw callback medians and the raw reference itself show A/A up to ±27–38%. So the Java → JS return-value change (callback.objectReturn() -> Object: −1.7% raw, −3.9% normalized) is not measured by this harness. Note too that the reference callback goes through the same code, so normalizing by it would cancel out any change that speeds up every callback.

Does your commit message include the wording below to reference a specific issue in this repo?

No.

Related Pull Requests

Does your pull request have unit tests?

No new specs: these are behavior-preserving changes, covered by the existing suite. The full suite (./gradlew runtestsAndVerifyResults, arm64 emulator, android-36.1 google_apis image) passes on the rebased branch: 1788 specs, 0 failures.

Summary by CodeRabbit

  • New Features
    • Added Java array benchmarks for indexed integer reads and writes, object reads, and callbacks returning objects.
  • Bug Fixes
    • Improved Java array access and value conversion, including handling primitive values and null references.
    • Improved management of converted Java references during calls between JavaScript and Java.

@coderabbitai

coderabbitai Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The JNI bridge now passes V8 isolates into array and argument conversion paths. Runtime metadata and V8 private-key handling change. The benchmark suite adds integer-array access, object-array reads, and an object-return callback benchmark.

Changes: JNI bridge and runtime

Layer / File(s) Summary
Isolate-aware indexed array access
test-app/runtime/src/main/cpp/ArrayElementAccessor.*, test-app/runtime/src/main/cpp/CallbackHandlers.*, test-app/runtime/src/main/cpp/MetadataNode.*, test-app/runtime/src/main/cpp/MethodCache.cpp
Array access now receives an explicit isolate. Primitive reads and writes use the array element type, while reference reads handle nulls, strings, and objects. Call sites pass the isolate to array access and metadata lookup.
Argument conversion and JNI reference ownership
test-app/runtime/src/main/cpp/ArgConverter.h, test-app/runtime/src/main/cpp/FieldAccessor.cpp, test-app/runtime/src/main/cpp/JEnv.*, test-app/runtime/src/main/cpp/JsArgConverter.*, test-app/runtime/src/main/cpp/JsArgToArrayConverter.*, test-app/runtime/src/main/cpp/NumericCasts.*, test-app/runtime/src/main/cpp/Runtime.cpp
Conversion helpers now receive explicit isolates. JsArgToArrayConverter tracks converted JNI references and can release its first converted argument to the caller. ConvertJsValueToJavaObject returns that released argument.
Runtime metadata and V8 state
test-app/runtime/src/main/cpp/ManualInstrumentation.h, test-app/runtime/src/main/cpp/MetadataEntry.*, test-app/runtime/src/main/cpp/MetadataNode.*, test-app/runtime/src/main/cpp/Runtime.*, test-app/runtime/src/main/cpp/V8StringConstants.*, test-app/runtime/src/main/cpp/CallbackHandlers.cpp
Runtime accessors move inline, metadata getters use inline cache checks, and V8 property names and private keys use persistent handles. Class construction, runtime lookup, and instrumentation name storage also change.
Array and callback benchmarks
test-app/app/src/main/assets/app/tests/benchmarks/jniBenchmarks.js, test-app/app/src/main/java/com/tns/tests/JniBench.java
The benchmark setup adds integer-array reads and writes, object-array reads, and an object-return callback benchmark. runCallbacks handles callback kind 8 and checks that the last result is not null.

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Refactor

Suggested reviewers: darind, ammarahm-ed, petekanev

Merge Risk: Minimal · up to fa1b3

This change trims per-call work on the JS-to-Java bridge and adds array and callback benchmarks. Inspection found no concrete regression in the changed paths. The author reports a passing emulator test run of 1,788 specs, and no additional merge-blocking risk is evident.

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): hot-path quick wins on the JNI bridge" matches the main objective. The changeset reduces per-call work on the JS-Java bridge through fewer copies and allocations, cached isol…
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): hot-path quick wins on the JNI bridge" matches the main objective. The changeset reduces per-call work on the JS-Java bridge through fewer copies and allocations, cached isolate keys, inlined accessors, and faster array element access. It also adds benchmark fixtures. The title names the performance focus and the JNI bridge, so it is specific. It does not name every part, such as the Runtime accessor removals, 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 719f538 and fa1b3e4.

Files selected for processing: 26

  • test-app/app/src/main/assets/app/tests/benchmarks/jniBenchmarks.js
  • test-app/app/src/main/java/com/tns/tests/JniBench.java
  • test-app/runtime/src/main/cpp/ArgConverter.h
  • test-app/runtime/src/main/cpp/ArrayElementAccessor.cpp
  • test-app/runtime/src/main/cpp/ArrayElementAccessor.h
  • test-app/runtime/src/main/cpp/CallbackHandlers.cpp
  • test-app/runtime/src/main/cpp/CallbackHandlers.h
  • test-app/runtime/src/main/cpp/FieldAccessor.cpp
  • test-app/runtime/src/main/cpp/JEnv.cpp
  • test-app/runtime/src/main/cpp/JEnv.h
  • test-app/runtime/src/main/cpp/JsArgConverter.cpp
  • test-app/runtime/src/main/cpp/JsArgConverter.h
  • test-app/runtime/src/main/cpp/JsArgToArrayConverter.cpp
  • test-app/runtime/src/main/cpp/JsArgToArrayConverter.h
  • test-app/runtime/src/main/cpp/ManualInstrumentation.h
  • test-app/runtime/src/main/cpp/MetadataEntry.cpp
  • test-app/runtime/src/main/cpp/MetadataEntry.h
  • test-app/runtime/src/main/cpp/MetadataNode.cpp
  • test-app/runtime/src/main/cpp/MetadataNode.h
  • test-app/runtime/src/main/cpp/MethodCache.cpp
  • test-app/runtime/src/main/cpp/NumericCasts.cpp
  • test-app/runtime/src/main/cpp/NumericCasts.h
  • test-app/runtime/src/main/cpp/Runtime.cpp
  • test-app/runtime/src/main/cpp/Runtime.h
  • test-app/runtime/src/main/cpp/V8StringConstants.cpp
  • test-app/runtime/src/main/cpp/V8StringConstants.h
Files with no reviewable changes: 1

  • test-app/runtime/src/main/cpp/JEnv.cpp

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

Adds JNI benchmark rows for reading and writing Java array elements
(int[] and Object[]) and for a Java -> JS callback that returns an
object, which the existing rows did not exercise.
- JsArgConverter::ConvertArg zero-filled a 1 KB error buffer for every
  argument; only a NUL-terminated prefix is ever read, so terminate it
  instead.
- The object/cast branch of ConvertArg created an unused JEnv (an
  emulated-TLS read) and looked up the runtime for every object argument;
  the object manager is now resolved once per converter, and only when a
  plain object argument needs it. The destructor skips its JEnv when no
  local refs were recorded.
- instrumentation::Frame copied its name into a std::string, so every
  TNSPERF() frame (class, extended-class and interface constructors,
  GetImplementationObject) heap-allocated for names longer than the SSO
  buffer even with instrumentation off. Literal and __func__ names are
  now kept as pointers; dynamic names still own a copy.
- The class, extended-class and interface constructor callbacks copied
  their class names per `new`; they now pass the stored names by
  reference and build the "-defaults" name only when it is needed.
Isolate::GetCurrent() and Runtime lookups are thread-local reads
(emulated TLS below API 29) that several per-call helpers repeated even
though their callers already held the isolate or the runtime.

- ArgConverter::ConvertToJavaString, NumericCasts::GetCastValue,
  MetadataNode::GetNodeFromHandle, the single-value JsArgToArrayConverter
  and the array element accessors now take the isolate from their caller.
- CallJavaMethod looked the runtime up twice per call; it reuses the
  first lookup.
- The instance field getter and setter looked up the runtime only to
  call the static ObjectManager::IsJsRuntimeObject.
Runtime::GetIsolate/GetJavaRuntime/GetObjectManager/GetContext/GetId,
JEnv's JNIEnv* conversion and the MetadataEntry getters were out-of-line
calls in the runtime's own library, made several times per JS <-> Java
call. They are now inline; the MetadataEntry getters inline only the
check for an already-read value and keep reading the metadata out of
line.

The Runtime definitions sit after the class so its declarations are left
as they are.
- A JS value returned to Java went through a JsArgToArrayConverter that
  heap-allocated a one-slot array and a vector entry, deleted a null
  global ref, and copied the converted local ref only to delete the
  original. The single-value converter now converts into an inline slot,
  and ConvertJsValueToJavaObject takes ownership of the converted local
  ref (a borrowed ref is still copied into a new local).
- CreateJSInstanceNative read the instance's class name back through
  GetObjectClass + Class.getName even though Java passes that same name.
- Java array element access copied the element signature and compared
  it against up to nine strings per access; it now switches on the
  element type. Object elements go through
  ObjectManager::GetOrCreateJSWrapper like method results and field
  reads do, instead of GetOrCreateObjectId + GetClassName + a node
  lookup under the global node mutex.
- The implementation-object, "supervalue" and "typemetadata" private
  keys were rebuilt from strings (and resolved through V8's private
  symbol registry) on every constructor call, `super` read and
  GetTypeMetadata. They are now created once per isolate in
  V8StringConstants next to the existing private keys; Private::ForApi
  on the same names yields the same symbols.
- Kotlin property accessors copied the accessor method's name and
  created a fresh V8 string per get/set; PropertyCallbackData now holds
  the internalized names.
- CreateArrayWrapper looked up the java/lang/Object node under the
  global node mutex for every Java array it wrapped; nodes are shared by
  all runtimes and never freed, so the pointer is resolved once.
- MethodCallback decoded its External twice.
@edusperoni
edusperoni force-pushed the perf/hot-path-quick-wins branch from 0412546 to fa1b3e4 Compare November 21, 2026 19:49
@edusperoni
edusperoni changed the base branch from main to fix/nested-object-array-element November 21, 2026 19:49
@edusperoni
edusperoni added this pull request to stack #2144 November 21, 2026 19:50
@edusperoni
edusperoni marked this pull request as ready for review November 21, 2026 19:52
@edusperoni
edusperoni merged commit 56c7b0b into main Nov 21, 2026
8 checks passed
@edusperoni
edusperoni deleted the perf/hot-path-quick-wins branch November 21, 2026 20:04
edusperoni added a commit that referenced this pull request Nov 21, 2026
### Description

**Current behavior.** Reading an element of a nested object array
crashes the app. For example, `outer[0]` where `outer` is a
`String[][]`:

```js
var strings = java.lang.reflect.Array.newInstance(java.lang.String.class, [2, 3]);
var row = strings[1]; // aborts
```

When the element has no JS wrapper yet,
`ArrayElementAccessor::ConvertToJsValue` names the new wrapper from the
declared element signature, passed through
`Util::JniClassPathToCanonicalName`. For `[Ljava/lang/String;` that
yields `"[java.lang.String"`, which is not a JNI class name.
`ObjectManager::CreateJSWrapperHelper` passes it to `FindClass`. A debug
build of `main` running the new spec on an arm64 emulator aborts under
CheckJNI:

```
JNI DETECTED ERROR IN APPLICATION: illegal class name '[java.lang.String'
    (should be of the form 'package/Class', [Lpackage/Class;' or '[[B')
    in call to FindClass
```

The name is also not one the metadata reader resolves: it splits names
on `/` and `$` only. The wrapper's node name is later read back as the
array signature for indexing into that element.

**New behavior.** The element's wrapper is named after its runtime class
(`ObjectManager::GetClassName`, e.g. `[Ljava/lang/String;`). Nested
arrays returned from methods or read from fields are already named this
way. Non-array elements already took this branch and are unchanged.

Nested primitive arrays (`int[][]`) were not affected, since their
canonical and JNI names are the same (`[I`). I checked this on `main`:
the new `int[][]` spec passes there without the fix. The same is true of
the new `Class`/`null` element spec.

### Does your commit message include the wording below to reference a
specific issue in this repo?
No.

### Related Pull Requests
Split out of #2141, which is stacked on this branch.

### Does your pull request have [unit
tests](https://github.com/NativeScript/NativeScript/blob/master/running-tests.md)?
Yes. `java-array-test.js` gains specs for reading and writing elements
of nested object arrays (`String[][]`) and nested primitive arrays
(`int[][]`), and for `Class` and `null` elements of an `Object[]`. The
full suite passes on an arm64 emulator (android-36.1 google_apis image):
1788 specs, 0 failures.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Bug Fixes**
* Improved handling of nested Java arrays, including reading and
updating elements while preserving row identity and type information.
* Java objects stored in object arrays now retain their runtime class
when accessed, and uninitialized elements remain `null`.
* These changes support arrays created dynamically through Java
reflection.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
edusperoni added a commit that referenced this pull request Nov 22, 2026
### 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 #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 #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
- #2137 merges cleanly with this branch (`git merge-tree`). It keeps its
two hot caches as `Runtime` members, and that is unchanged here.

### 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.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## 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.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
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