Skip to content

Commit f103fd0

Browse files
authored
perf(runtime): cheaper runtime and RuntimeState lookups (#2146)
### 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 -->
1 parent 7546ca1 commit f103fd0

4 files changed

Lines changed: 114 additions & 78 deletions

File tree

‎test-app/runtime/src/main/cpp/Runtime.cpp‎

Lines changed: 9 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -145,14 +145,7 @@ Runtime::Runtime(JNIEnv* env, jobject runtime, int id)
145145
}
146146
}
147147

148-
Runtime* Runtime::GetRuntime(int runtimeId) {
149-
// A runtime is only destroyed on its own thread, which is busy in this call,
150-
// so the calling thread's own runtime needs neither the lock nor the map.
151-
auto& current = s_current;
152-
if (runtimeId == current.id) {
153-
return current.runtime;
154-
}
155-
148+
Runtime* Runtime::GetRuntimeSlow(int runtimeId) {
156149
Runtime* runtime = nullptr;
157150
{
158151
std::lock_guard<std::mutex> lock(s_runtimeCacheMutex);
@@ -169,18 +162,8 @@ Runtime* Runtime::GetRuntime(int runtimeId) {
169162
return runtime;
170163
}
171164

172-
Runtime* Runtime::GetRuntime(v8::Isolate* isolate) {
173-
/*
174-
* Hot path, called from V8 callbacks on the isolate's own thread. The slot
175-
* is written once in PrepareV8Runtime before the isolate runs any JS, so
176-
* reading it requires no lock.
177-
*/
178-
auto runtime = TryGetRuntime(isolate);
179-
if (runtime != nullptr) {
180-
return runtime;
181-
}
182-
183-
// covers the window during isolate setup before SetData has run
165+
Runtime* Runtime::GetRuntimeSlow(v8::Isolate* isolate) {
166+
Runtime* runtime;
184167
{
185168
std::lock_guard<std::mutex> lock(s_runtimeCacheMutex);
186169
auto it = s_isolate2RuntimesCache.find(isolate);
@@ -196,18 +179,6 @@ Runtime* Runtime::GetRuntime(v8::Isolate* isolate) {
196179
return runtime;
197180
}
198181

199-
Runtime* Runtime::GetRuntimeFromIsolateData(v8::Isolate* isolate) {
200-
auto runtime = TryGetRuntime(isolate);
201-
202-
if (runtime == nullptr) {
203-
stringstream ss;
204-
ss << "Cannot find runtime for isolate: " << isolate;
205-
throw NativeScriptException(ss.str());
206-
}
207-
208-
return runtime;
209-
}
210-
211182
ObjectManager* Runtime::GetObjectManager(v8::Isolate* isolate) {
212183
return GetRuntime(isolate)->GetObjectManager();
213184
}
@@ -600,9 +571,10 @@ struct CallbackMethodNames {
600571
std::vector<v8::Global<v8::String>> byId;
601572
};
602573

603-
Local<String> GetCallbackMethodName(Isolate* isolate, JNIEnv* env,
604-
jstring methodName, jint methodNameId) {
605-
auto* names = RuntimeState::For<CallbackMethodNames>(isolate);
574+
Local<String> GetCallbackMethodName(Runtime* runtime, Isolate* isolate,
575+
JNIEnv* env, jstring methodName,
576+
jint methodNameId) {
577+
auto* names = RuntimeState::For<CallbackMethodNames>(runtime);
606578
if (names == nullptr || methodNameId < 0) {
607579
return ArgConverter::jstringToInternalizedV8String(isolate, env, methodName);
608580
}
@@ -664,7 +636,7 @@ jobject Runtime::CallJSMethodNative(JNIEnv* _env, jobject obj,
664636
jsObject->GetIdentityHash());
665637

666638
auto jsMethodName =
667-
GetCallbackMethodName(m_isolate, _env, methodName, methodNameId);
639+
GetCallbackMethodName(this, m_isolate, _env, methodName, methodNameId);
668640
auto jsResult = CallbackHandlers::CallJSMethod(m_isolate, env, jsObject,
669641
jsMethodName, args);
670642

@@ -1410,7 +1382,7 @@ v8::Platform* Runtime::platform = nullptr;
14101382
int Runtime::m_androidVersion = Runtime::GetAndroidVersion();
14111383
std::shared_ptr<EventLoop> Runtime::s_mainEventLoop;
14121384

1413-
thread_local Runtime::CurrentRuntime Runtime::s_current;
1385+
constinit thread_local Runtime::CurrentRuntime Runtime::s_current;
14141386
thread_local PendingIsolateSetup Runtime::s_pendingIsolateSetup;
14151387

14161388
void Runtime::SetPendingIsolateSetup(PendingIsolateSetup setup) {

‎test-app/runtime/src/main/cpp/Runtime.h‎

Lines changed: 32 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -85,11 +85,28 @@ class Runtime {
8585
*/
8686
static void SetPendingIsolateSetup(PendingIsolateSetup setup);
8787

88-
static Runtime* GetRuntime(int runtimeId);
89-
90-
static Runtime* GetRuntime(v8::Isolate* isolate);
88+
static Runtime* GetRuntime(int runtimeId) {
89+
// A runtime is only destroyed on its own thread, which is busy in
90+
// this call, so the calling thread's own runtime needs neither the
91+
// lock nor the map.
92+
auto& current = s_current;
93+
if (runtimeId == current.id) [[likely]] {
94+
return current.runtime;
95+
}
96+
return GetRuntimeSlow(runtimeId);
97+
}
9198

92-
static Runtime* GetRuntimeFromIsolateData(v8::Isolate* isolate);
99+
/*
100+
* Hot path, called from V8 callbacks on the isolate's own thread. The
101+
* slot is written once in PrepareV8Runtime before the isolate runs any
102+
* JS, so reading it requires no lock.
103+
*/
104+
static Runtime* GetRuntime(v8::Isolate* isolate) {
105+
if (auto* runtime = TryGetRuntime(isolate)) [[likely]] {
106+
return runtime;
107+
}
108+
return GetRuntimeSlow(isolate);
109+
}
93110

94111
/*
95112
* The runtime for this isolate, or null. Unlike the accessors above it
@@ -363,6 +380,14 @@ class Runtime {
363380
}
364381

365382
private:
383+
// Another thread's runtime, looked up under the lock; throws when the
384+
// id names no live runtime.
385+
static Runtime* GetRuntimeSlow(int runtimeId);
386+
387+
// Covers the window during isolate setup before the data slot is set;
388+
// throws when the isolate has no runtime.
389+
static Runtime* GetRuntimeSlow(v8::Isolate* isolate);
390+
366391
Runtime(JNIEnv* env, jobject runtime, int id);
367392

368393
int m_id;
@@ -490,7 +515,9 @@ class Runtime {
490515
Runtime* runtime = nullptr;
491516
int id = -1;
492517
};
493-
static thread_local CurrentRuntime s_current;
518+
// constinit lets other translation units read it without first
519+
// calling its thread-local initialization hook.
520+
static constinit thread_local CurrentRuntime s_current;
494521
static thread_local PendingIsolateSetup s_pendingIsolateSetup;
495522

496523
#ifdef APPLICATION_IN_DEBUG
Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,36 @@
11
#include "RuntimeState.h"
22

3+
#include <atomic>
4+
5+
#include "NativeScriptAssert.h"
6+
37
namespace tns {
48

5-
size_t RuntimeState::NextSlotIndex() {
6-
// Slot indices are claimed the first time a state type is used, which can
7-
// happen on any runtime's thread -- two workers touching two different
8-
// subsystems for the first time race here.
9+
size_t RuntimeState::ClaimSlotIndex() {
10+
// Constant-initialized: called from the dynamic initializers of
11+
// RuntimeState::kSlotIndex, in whatever order the library runs them.
912
static std::atomic<size_t> next{0};
10-
return next.fetch_add(1, std::memory_order_relaxed);
13+
size_t index = next.fetch_add(1, std::memory_order_relaxed);
14+
NS_CHECK(index < kCapacity);
15+
return index;
16+
}
17+
18+
void RuntimeState::Clear() {
19+
disposed_ = true;
20+
21+
// Every slot is emptied before any state is destroyed, so a destructor
22+
// that looks up state, its own included, gets null.
23+
void* values[kCapacity];
24+
for (size_t i = 0; i < kCapacity; i++) {
25+
values[i] = slots_[i];
26+
slots_[i] = nullptr;
27+
}
28+
29+
for (size_t i = kCapacity; i-- > 0;) {
30+
if (values[i] != nullptr) {
31+
deleters_[i](values[i]);
32+
}
33+
}
1134
}
1235

1336
} // namespace tns

‎test-app/runtime/src/main/cpp/RuntimeState.h‎

Lines changed: 45 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,7 @@
11
#ifndef TEST_APP_RUNTIMESTATE_H
22
#define TEST_APP_RUNTIMESTATE_H
33

4-
#include <atomic>
54
#include <cstddef>
6-
#include <memory>
7-
#include <vector>
85

96
#include "Runtime.h"
107
#include "v8.h"
@@ -23,7 +20,7 @@ namespace tns {
2320
*
2421
* Hanging the state off the Runtime removes the sharing instead of guarding it:
2522
* nothing is shared, so there is nothing to race on and no lock on the access
26-
* path (a lookup is an isolate data-slot read plus a vector index). It also
23+
* path (a lookup is an isolate data-slot read plus an array index). It also
2724
* removes the per-isolate erase at teardown -- the whole bag is destroyed once,
2825
* on the runtime's own thread, while the isolate is still alive, which is what
2926
* v8::Persistent members require.
@@ -34,6 +31,8 @@ namespace tns {
3431
* auto* state = RuntimeState::For<MyState>(isolate);
3532
* if (state == nullptr) return; // runtime is tearing down
3633
*
34+
* or with For<MyState>(runtime) where the Runtime is already at hand.
35+
*
3736
* The first call for a runtime default-constructs the state; it is destroyed
3837
* with the runtime.
3938
*/
@@ -47,49 +46,59 @@ class RuntimeState {
4746
template <typename T>
4847
static T* For(v8::Isolate* isolate);
4948

49+
template <typename T>
50+
static T* For(Runtime* runtime);
51+
52+
~RuntimeState() {
53+
Clear();
54+
}
55+
5056
/*
5157
* Destroys every state object. Runs on the runtime's own thread from
5258
* DestroyRuntime, before the isolate is disposed.
5359
*/
54-
void Clear() {
55-
disposed_ = true;
56-
slots_.clear();
57-
}
60+
void Clear();
61+
62+
// More state types than this abort the library load; raise it then.
63+
static constexpr size_t kCapacity = 32;
5864

5965
private:
60-
// One slot index per state type, handed out on first use from any thread.
61-
static size_t NextSlotIndex();
66+
static size_t ClaimSlotIndex();
6267

68+
// One slot index per state type, claimed while the library loads so a
69+
// lookup reads a plain constant instead of a function-local static's
70+
// guard. ClaimSlotIndex's counter is constant-initialized, so it is ready
71+
// whichever translation unit's initializers run first.
6372
template <typename T>
64-
static size_t SlotIndexFor() {
65-
static const size_t index = NextSlotIndex();
66-
return index;
67-
}
73+
static inline const size_t kSlotIndex = ClaimSlotIndex();
6874

69-
// Type-erased so Runtime need not know any subsystem's state type; the
70-
// deleter restores the type at destruction.
71-
using Slot = std::unique_ptr<void, void (*)(void*)>;
75+
template <typename T>
76+
T* Get() {
77+
if (void* value = slots_[kSlotIndex<T>]) [[likely]] {
78+
return static_cast<T*>(value);
79+
}
80+
return Create<T>();
81+
}
7282

7383
template <typename T>
74-
T* GetOrCreate() {
84+
[[gnu::noinline]] T* Create() {
85+
// Clear empties every slot, so a lookup during or after teardown
86+
// ends up here.
7587
if (disposed_) {
7688
return nullptr;
7789
}
7890

79-
size_t index = SlotIndexFor<T>();
80-
while (slots_.size() <= index) {
81-
slots_.emplace_back(nullptr, [](void*) {});
82-
}
83-
84-
Slot& slot = slots_[index];
85-
if (slot == nullptr) {
86-
slot = Slot(new T(), [](void* value) { delete static_cast<T*>(value); });
87-
}
88-
89-
return static_cast<T*>(slot.get());
91+
const size_t index = kSlotIndex<T>;
92+
T* value = new T();
93+
slots_[index] = value;
94+
deleters_[index] = [](void* p) { delete static_cast<T*>(p); };
95+
return value;
9096
}
9197

92-
std::vector<Slot> slots_;
98+
// Type-erased so Runtime need not know any subsystem's state type; the
99+
// deleter restores the type at destruction.
100+
void* slots_[kCapacity] = {};
101+
void (*deleters_[kCapacity])(void*) = {};
93102
bool disposed_ = false;
94103
};
95104

@@ -102,12 +111,17 @@ T* RuntimeState::For(v8::Isolate* isolate) {
102111
return nullptr;
103112
}
104113

114+
return For<T>(runtime);
115+
}
116+
117+
template <typename T>
118+
T* RuntimeState::For(Runtime* runtime) {
105119
RuntimeState* state = runtime->GetState();
106120
if (state == nullptr) {
107121
return nullptr;
108122
}
109123

110-
return state->GetOrCreate<T>();
124+
return state->Get<T>();
111125
}
112126

113127
} // namespace tns

0 commit comments

Comments
 (0)