Skip to content

Commit 7e43b8d

Browse files
committed
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.
1 parent 112a380 commit 7e43b8d

3 files changed

Lines changed: 78 additions & 40 deletions

File tree

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

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -571,9 +571,10 @@ struct CallbackMethodNames {
571571
std::vector<v8::Global<v8::String>> byId;
572572
};
573573

574-
Local<String> GetCallbackMethodName(Isolate* isolate, JNIEnv* env,
575-
jstring methodName, jint methodNameId) {
576-
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);
577578
if (names == nullptr || methodNameId < 0) {
578579
return ArgConverter::jstringToInternalizedV8String(isolate, env, methodName);
579580
}
@@ -634,7 +635,7 @@ jobject Runtime::CallJSMethodNative(JNIEnv* _env, jobject obj,
634635
jsObject->GetIdentityHash());
635636

636637
auto jsMethodName =
637-
GetCallbackMethodName(m_isolate, _env, methodName, methodNameId);
638+
GetCallbackMethodName(this, m_isolate, _env, methodName, methodNameId);
638639
auto jsResult = CallbackHandlers::CallJSMethod(m_isolate, env, jsObject,
639640
jsMethodName, args);
640641

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)