From 8077a996ca4a99e58596fb0f4d12fd11fbd9cc62 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 16:44:12 -0300 Subject: [PATCH 1/2] perf(runtime): inline the runtime lookups' fast paths 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. --- test-app/runtime/src/main/cpp/Runtime.cpp | 37 +++-------------------- test-app/runtime/src/main/cpp/Runtime.h | 37 ++++++++++++++++++++--- 2 files changed, 36 insertions(+), 38 deletions(-) diff --git a/test-app/runtime/src/main/cpp/Runtime.cpp b/test-app/runtime/src/main/cpp/Runtime.cpp index 6698dc230..d076ec20b 100644 --- a/test-app/runtime/src/main/cpp/Runtime.cpp +++ b/test-app/runtime/src/main/cpp/Runtime.cpp @@ -145,14 +145,7 @@ Runtime::Runtime(JNIEnv* env, jobject runtime, int id) } } -Runtime* Runtime::GetRuntime(int runtimeId) { - // A runtime is only destroyed on its own thread, which is busy in this call, - // so the calling thread's own runtime needs neither the lock nor the map. - auto& current = s_current; - if (runtimeId == current.id) { - return current.runtime; - } - +Runtime* Runtime::GetRuntimeSlow(int runtimeId) { Runtime* runtime = nullptr; { std::lock_guard lock(s_runtimeCacheMutex); @@ -169,18 +162,8 @@ Runtime* Runtime::GetRuntime(int runtimeId) { return runtime; } -Runtime* Runtime::GetRuntime(v8::Isolate* isolate) { - /* - * Hot path, called from V8 callbacks on the isolate's own thread. The slot - * is written once in PrepareV8Runtime before the isolate runs any JS, so - * reading it requires no lock. - */ - auto runtime = TryGetRuntime(isolate); - if (runtime != nullptr) { - return runtime; - } - - // covers the window during isolate setup before SetData has run +Runtime* Runtime::GetRuntimeSlow(v8::Isolate* isolate) { + Runtime* runtime; { std::lock_guard lock(s_runtimeCacheMutex); auto it = s_isolate2RuntimesCache.find(isolate); @@ -196,18 +179,6 @@ Runtime* Runtime::GetRuntime(v8::Isolate* isolate) { return runtime; } -Runtime* Runtime::GetRuntimeFromIsolateData(v8::Isolate* isolate) { - auto runtime = TryGetRuntime(isolate); - - if (runtime == nullptr) { - stringstream ss; - ss << "Cannot find runtime for isolate: " << isolate; - throw NativeScriptException(ss.str()); - } - - return runtime; -} - ObjectManager* Runtime::GetObjectManager(v8::Isolate* isolate) { return GetRuntime(isolate)->GetObjectManager(); } @@ -1410,7 +1381,7 @@ v8::Platform* Runtime::platform = nullptr; int Runtime::m_androidVersion = Runtime::GetAndroidVersion(); std::shared_ptr Runtime::s_mainEventLoop; -thread_local Runtime::CurrentRuntime Runtime::s_current; +constinit thread_local Runtime::CurrentRuntime Runtime::s_current; thread_local PendingIsolateSetup Runtime::s_pendingIsolateSetup; void Runtime::SetPendingIsolateSetup(PendingIsolateSetup setup) { diff --git a/test-app/runtime/src/main/cpp/Runtime.h b/test-app/runtime/src/main/cpp/Runtime.h index 0dee7b1a7..114ad012d 100644 --- a/test-app/runtime/src/main/cpp/Runtime.h +++ b/test-app/runtime/src/main/cpp/Runtime.h @@ -85,11 +85,28 @@ class Runtime { */ static void SetPendingIsolateSetup(PendingIsolateSetup setup); - static Runtime* GetRuntime(int runtimeId); - - static Runtime* GetRuntime(v8::Isolate* isolate); + static Runtime* GetRuntime(int runtimeId) { + // A runtime is only destroyed on its own thread, which is busy in + // this call, so the calling thread's own runtime needs neither the + // lock nor the map. + auto& current = s_current; + if (runtimeId == current.id) [[likely]] { + return current.runtime; + } + return GetRuntimeSlow(runtimeId); + } - static Runtime* GetRuntimeFromIsolateData(v8::Isolate* isolate); + /* + * Hot path, called from V8 callbacks on the isolate's own thread. The + * slot is written once in PrepareV8Runtime before the isolate runs any + * JS, so reading it requires no lock. + */ + static Runtime* GetRuntime(v8::Isolate* isolate) { + if (auto* runtime = TryGetRuntime(isolate)) [[likely]] { + return runtime; + } + return GetRuntimeSlow(isolate); + } /* * The runtime for this isolate, or null. Unlike the accessors above it @@ -363,6 +380,14 @@ class Runtime { } private: + // Another thread's runtime, looked up under the lock; throws when the + // id names no live runtime. + static Runtime* GetRuntimeSlow(int runtimeId); + + // Covers the window during isolate setup before the data slot is set; + // throws when the isolate has no runtime. + static Runtime* GetRuntimeSlow(v8::Isolate* isolate); + Runtime(JNIEnv* env, jobject runtime, int id); int m_id; @@ -490,7 +515,9 @@ class Runtime { Runtime* runtime = nullptr; int id = -1; }; - static thread_local CurrentRuntime s_current; + // constinit lets other translation units read it without first + // calling its thread-local initialization hook. + static constinit thread_local CurrentRuntime s_current; static thread_local PendingIsolateSetup s_pendingIsolateSetup; #ifdef APPLICATION_IN_DEBUG From 5a634ee0503e65c1b0e38f6514b94b84ee17f354 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 16:45:14 -0300 Subject: [PATCH 2/2] perf(runtime): make RuntimeState lookups cheaper 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. --- test-app/runtime/src/main/cpp/Runtime.cpp | 9 ++- .../runtime/src/main/cpp/RuntimeState.cpp | 33 ++++++-- test-app/runtime/src/main/cpp/RuntimeState.h | 76 +++++++++++-------- 3 files changed, 78 insertions(+), 40 deletions(-) diff --git a/test-app/runtime/src/main/cpp/Runtime.cpp b/test-app/runtime/src/main/cpp/Runtime.cpp index d076ec20b..262cc2536 100644 --- a/test-app/runtime/src/main/cpp/Runtime.cpp +++ b/test-app/runtime/src/main/cpp/Runtime.cpp @@ -571,9 +571,10 @@ struct CallbackMethodNames { std::vector> byId; }; -Local GetCallbackMethodName(Isolate* isolate, JNIEnv* env, - jstring methodName, jint methodNameId) { - auto* names = RuntimeState::For(isolate); +Local GetCallbackMethodName(Runtime* runtime, Isolate* isolate, + JNIEnv* env, jstring methodName, + jint methodNameId) { + auto* names = RuntimeState::For(runtime); if (names == nullptr || methodNameId < 0) { return ArgConverter::jstringToInternalizedV8String(isolate, env, methodName); } @@ -635,7 +636,7 @@ jobject Runtime::CallJSMethodNative(JNIEnv* _env, jobject obj, jsObject->GetIdentityHash()); auto jsMethodName = - GetCallbackMethodName(m_isolate, _env, methodName, methodNameId); + GetCallbackMethodName(this, m_isolate, _env, methodName, methodNameId); auto jsResult = CallbackHandlers::CallJSMethod(m_isolate, env, jsObject, jsMethodName, args); diff --git a/test-app/runtime/src/main/cpp/RuntimeState.cpp b/test-app/runtime/src/main/cpp/RuntimeState.cpp index fbfef1652..0ca6bd4da 100644 --- a/test-app/runtime/src/main/cpp/RuntimeState.cpp +++ b/test-app/runtime/src/main/cpp/RuntimeState.cpp @@ -1,13 +1,36 @@ #include "RuntimeState.h" +#include + +#include "NativeScriptAssert.h" + namespace tns { -size_t RuntimeState::NextSlotIndex() { - // Slot indices are claimed the first time a state type is used, which can - // happen on any runtime's thread -- two workers touching two different - // subsystems for the first time race here. +size_t RuntimeState::ClaimSlotIndex() { + // Constant-initialized: called from the dynamic initializers of + // RuntimeState::kSlotIndex, in whatever order the library runs them. static std::atomic next{0}; - return next.fetch_add(1, std::memory_order_relaxed); + size_t index = next.fetch_add(1, std::memory_order_relaxed); + NS_CHECK(index < kCapacity); + return index; +} + +void RuntimeState::Clear() { + disposed_ = true; + + // Every slot is emptied before any state is destroyed, so a destructor + // that looks up state, its own included, gets null. + void* values[kCapacity]; + for (size_t i = 0; i < kCapacity; i++) { + values[i] = slots_[i]; + slots_[i] = nullptr; + } + + for (size_t i = kCapacity; i-- > 0;) { + if (values[i] != nullptr) { + deleters_[i](values[i]); + } + } } } // namespace tns diff --git a/test-app/runtime/src/main/cpp/RuntimeState.h b/test-app/runtime/src/main/cpp/RuntimeState.h index 7723db7b0..676b30522 100644 --- a/test-app/runtime/src/main/cpp/RuntimeState.h +++ b/test-app/runtime/src/main/cpp/RuntimeState.h @@ -1,10 +1,7 @@ #ifndef TEST_APP_RUNTIMESTATE_H #define TEST_APP_RUNTIMESTATE_H -#include #include -#include -#include #include "Runtime.h" #include "v8.h" @@ -23,7 +20,7 @@ namespace tns { * * Hanging the state off the Runtime removes the sharing instead of guarding it: * nothing is shared, so there is nothing to race on and no lock on the access - * path (a lookup is an isolate data-slot read plus a vector index). It also + * path (a lookup is an isolate data-slot read plus an array index). It also * removes the per-isolate erase at teardown -- the whole bag is destroyed once, * on the runtime's own thread, while the isolate is still alive, which is what * v8::Persistent members require. @@ -34,6 +31,8 @@ namespace tns { * auto* state = RuntimeState::For(isolate); * if (state == nullptr) return; // runtime is tearing down * + * or with For(runtime) where the Runtime is already at hand. + * * The first call for a runtime default-constructs the state; it is destroyed * with the runtime. */ @@ -47,49 +46,59 @@ class RuntimeState { template static T* For(v8::Isolate* isolate); + template + static T* For(Runtime* runtime); + + ~RuntimeState() { + Clear(); + } + /* * Destroys every state object. Runs on the runtime's own thread from * DestroyRuntime, before the isolate is disposed. */ - void Clear() { - disposed_ = true; - slots_.clear(); - } + void Clear(); + + // More state types than this abort the library load; raise it then. + static constexpr size_t kCapacity = 32; private: - // One slot index per state type, handed out on first use from any thread. - static size_t NextSlotIndex(); + static size_t ClaimSlotIndex(); + // One slot index per state type, claimed while the library loads so a + // lookup reads a plain constant instead of a function-local static's + // guard. ClaimSlotIndex's counter is constant-initialized, so it is ready + // whichever translation unit's initializers run first. template - static size_t SlotIndexFor() { - static const size_t index = NextSlotIndex(); - return index; - } + static inline const size_t kSlotIndex = ClaimSlotIndex(); - // Type-erased so Runtime need not know any subsystem's state type; the - // deleter restores the type at destruction. - using Slot = std::unique_ptr; + template + T* Get() { + if (void* value = slots_[kSlotIndex]) [[likely]] { + return static_cast(value); + } + return Create(); + } template - T* GetOrCreate() { + [[gnu::noinline]] T* Create() { + // Clear empties every slot, so a lookup during or after teardown + // ends up here. if (disposed_) { return nullptr; } - size_t index = SlotIndexFor(); - while (slots_.size() <= index) { - slots_.emplace_back(nullptr, [](void*) {}); - } - - Slot& slot = slots_[index]; - if (slot == nullptr) { - slot = Slot(new T(), [](void* value) { delete static_cast(value); }); - } - - return static_cast(slot.get()); + const size_t index = kSlotIndex; + T* value = new T(); + slots_[index] = value; + deleters_[index] = [](void* p) { delete static_cast(p); }; + return value; } - std::vector slots_; + // Type-erased so Runtime need not know any subsystem's state type; the + // deleter restores the type at destruction. + void* slots_[kCapacity] = {}; + void (*deleters_[kCapacity])(void*) = {}; bool disposed_ = false; }; @@ -102,12 +111,17 @@ T* RuntimeState::For(v8::Isolate* isolate) { return nullptr; } + return For(runtime); +} + +template +T* RuntimeState::For(Runtime* runtime) { RuntimeState* state = runtime->GetState(); if (state == nullptr) { return nullptr; } - return state->GetOrCreate(); + return state->Get(); } } // namespace tns