From 2af2c338b6ad84d2d81b99bbd21d2b0f60280a20 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 10:56:41 -0300 Subject: [PATCH 1/3] perf(runtime): keep MethodCache's signature key scratch on the Runtime MethodCache encoded every overload-resolved call's and constructor's cache key into a `static thread_local std::string`. The runtime's minSdk is below 29, so that thread_local is emulated: every access goes through __emutls_get_address, and because the string has a destructor, through a second lookup of the TU's __tls_guard as well. A cache hit made three such calls, on every overload-resolved JS->Java call and every Java construction from JS (e.g. `new java.lang.Object()`). The key is only ever built by the thread holding the isolate's Locker, so a scratch string owned by the Runtime serves the same purpose without TLS. The key is still copied before resolving, because resolving calls into Java, which can call back into JS and reuse the scratch. --- test-app/runtime/src/main/cpp/MethodCache.cpp | 18 +++++++++--------- test-app/runtime/src/main/cpp/Runtime.h | 11 +++++++++++ 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/test-app/runtime/src/main/cpp/MethodCache.cpp b/test-app/runtime/src/main/cpp/MethodCache.cpp index e2fa1c371..c2e8e43a7 100644 --- a/test-app/runtime/src/main/cpp/MethodCache.cpp +++ b/test-app/runtime/src/main/cpp/MethodCache.cpp @@ -41,23 +41,22 @@ void MethodCache::Init() { NS_CHECK(RESOLVE_CONSTRUCTOR_SIGNATURE_ID != nullptr); } -// Reused for every lookup so a cache hit allocates nothing. -static thread_local std::string s_signatureKey; static const MethodCache::CacheMethodInfo s_unresolved; const MethodCache::CacheMethodInfo& MethodCache::ResolveMethodSignature(const string& className, const string& methodName, const FunctionCallbackInfo& args, bool isStatic) { CacheMethodInfo method_info; - EncodeSignature(s_signatureKey, className, methodName, args, isStatic); + auto& signatureKey = Runtime::GetRuntime(args.GetIsolate())->GetSignatureKeyScratch(); + EncodeSignature(signatureKey, className, methodName, args, isStatic); { std::shared_lock lock(signatureCacheMutex); - auto it = s_mthod_ctor_signature_cache.find(s_signatureKey); + auto it = s_mthod_ctor_signature_cache.find(signatureKey); if (it != s_mthod_ctor_signature_cache.end()) { return it->second; } } - // Resolving calls into Java, which may call back into JS and reuse s_signatureKey. - string encoded_method_signature = s_signatureKey; + // Resolving calls into Java, which may call back into JS and reuse the scratch key. + string encoded_method_signature = signatureKey; auto signature = ResolveJavaMethod(args, className, methodName); @@ -89,15 +88,16 @@ const MethodCache::CacheMethodInfo& MethodCache::ResolveConstructorSignature(con auto& args = argWrapper.args; static const string kConstructorName = ""; - EncodeSignature(s_signatureKey, fullClassName, kConstructorName, args, false); + auto& signatureKey = Runtime::GetRuntime(args.GetIsolate())->GetSignatureKeyScratch(); + EncodeSignature(signatureKey, fullClassName, kConstructorName, args, false); { std::shared_lock lock(signatureCacheMutex); - auto it = s_mthod_ctor_signature_cache.find(s_signatureKey); + auto it = s_mthod_ctor_signature_cache.find(signatureKey); if (it != s_mthod_ctor_signature_cache.end()) { return it->second; } } - string encoded_ctor_signature = s_signatureKey; + string encoded_ctor_signature = signatureKey; auto signature = ResolveConstructor(args, javaClass, isInterface); diff --git a/test-app/runtime/src/main/cpp/Runtime.h b/test-app/runtime/src/main/cpp/Runtime.h index 77913df69..c7380e2af 100644 --- a/test-app/runtime/src/main/cpp/Runtime.h +++ b/test-app/runtime/src/main/cpp/Runtime.h @@ -169,6 +169,15 @@ class Runtime { ObjectManager* GetObjectManager() const; + /* + * Scratch for MethodCache's signature keys, so a cache hit allocates + * nothing. Only for the thread holding the isolate, and not across a + * call that can re-enter JS. + */ + std::string& GetSignatureKeyScratch() { + return m_signatureKeyScratch; + } + AdmissionGate& GetAdmissionGate() { return m_admissionGate; } @@ -395,6 +404,8 @@ class Runtime { // Decided by ElectMainRuntime, before anything can read it. bool m_isMainThread = false; + std::string m_signatureKeyScratch; + // This isolate's performance time origin, captured at isolate // creation: the monotonic clock reading now() is relative to, and the // wall-clock milliseconds that reading corresponds to. From 2ea89e4719ad12444fb9802e490a5990dc3da8d1 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 10:56:58 -0300 Subject: [PATCH 2/3] perf(runtime): keep the default-overrides field cache on the Runtime SetDefaultOverrides cached each class's defaultOverrides__ns field in a function-local thread_local map. Below API 29 thread_locals are emulated, so every construction of an implementation with default-method overrides paid two __emutls_get_address lookups (the map and its thread_local initialization guard), and each thread that touched it registered a TLS destructor. Only the thread holding the isolate's Locker constructs instances, so the cache moves onto the Runtime. --- test-app/runtime/src/main/cpp/CallbackHandlers.cpp | 6 +++--- test-app/runtime/src/main/cpp/Runtime.h | 8 ++++++++ 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp index ae99e715d..f8f5777d1 100644 --- a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp +++ b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp @@ -151,8 +151,8 @@ namespace { * app has one, lacks the field and keeps its own behaviour. The class cache hands out one * global reference per class name for the life of the process, so it is a stable key. */ -void SetDefaultOverrides(JNIEnv* env, jobject instance, jclass clazz, uint64_t defaultOverrides) { - thread_local robin_hood::unordered_map fields; +void SetDefaultOverrides(Runtime* runtime, JNIEnv* env, jobject instance, jclass clazz, uint64_t defaultOverrides) { + auto& fields = runtime->GetDefaultOverridesFields(); jfieldID field; auto found = fields.find(clazz); @@ -263,7 +263,7 @@ bool CallbackHandlers::RegisterInstance(Isolate *isolate, const Local &j // Before any Java code but the constructor's own can see the instance. // An interface proxy's handler received the mask with the instance. if (defaultOverrides != 0 && instance != nullptr && !mi.isInterfaceProxy) { - SetDefaultOverrides(env, instance, generatedJavaClass, defaultOverrides); + SetDefaultOverrides(runtime, env, instance, generatedJavaClass, defaultOverrides); } jlong usedJavaMemory = env.CallLongMethod(runtime->GetJavaRuntime(), REGISTER_CONSTRUCTED_INSTANCE_ID, diff --git a/test-app/runtime/src/main/cpp/Runtime.h b/test-app/runtime/src/main/cpp/Runtime.h index c7380e2af..36844f76c 100644 --- a/test-app/runtime/src/main/cpp/Runtime.h +++ b/test-app/runtime/src/main/cpp/Runtime.h @@ -178,6 +178,12 @@ class Runtime { return m_signatureKeyScratch; } + // Each default-overriding class's defaultOverrides__ns field, or null + // when the class has none. Only for the thread holding the isolate. + robin_hood::unordered_map& GetDefaultOverridesFields() { + return m_defaultOverridesFields; + } + AdmissionGate& GetAdmissionGate() { return m_admissionGate; } @@ -406,6 +412,8 @@ class Runtime { std::string m_signatureKeyScratch; + robin_hood::unordered_map m_defaultOverridesFields; + // This isolate's performance time origin, captured at isolate // creation: the monotonic clock reading now() is relative to, and the // wall-clock milliseconds that reading corresponds to. From dffdbb3b1f225659c7a7085d528b929b29afd928 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 10:57:27 -0300 Subject: [PATCH 3/3] perf(runtime): track the looper callback depth on the EventLoop Every eventfd/timerfd ALooper callback incremented and decremented a thread_local depth counter. Below API 29 that thread_local is emulated, so each callback paid an __emutls_get_address lookup. The fd callbacks only run on the loop's home thread and already receive the EventLoop as their data pointer, so the depth becomes an EventLoop member and IsInLooperCallback() an instance method answering for that loop's home thread. It currently has no callers. --- test-app/runtime/src/main/cpp/EventLoop.cpp | 15 +++++---------- test-app/runtime/src/main/cpp/EventLoop.h | 16 ++++++++++------ 2 files changed, 15 insertions(+), 16 deletions(-) diff --git a/test-app/runtime/src/main/cpp/EventLoop.cpp b/test-app/runtime/src/main/cpp/EventLoop.cpp index e1fb5f4ee..9fed8fc91 100644 --- a/test-app/runtime/src/main/cpp/EventLoop.cpp +++ b/test-app/runtime/src/main/cpp/EventLoop.cpp @@ -792,18 +792,13 @@ EventLoop::PumpResult EventLoop::PumpUntil(double deadlineSeconds, } namespace { -// Depth, not a flag: an fd callback can dispatch JS that lands back in -// another callback through a nested drain. -thread_local int t_looperCallbackDepth = 0; - struct LooperCallbackScope { - LooperCallbackScope() { ++t_looperCallbackDepth; } - ~LooperCallbackScope() { --t_looperCallbackDepth; } + explicit LooperCallbackScope(int& depth) : depth_(depth) { ++depth_; } + ~LooperCallbackScope() { --depth_; } + int& depth_; }; } // namespace -bool EventLoop::IsInLooperCallback() { return t_looperCallbackDepth > 0; } - void EventLoop::WaitForInternalWork(int timeoutMs, bool pumpDeliverable) { const DrainFilter filter = pumpDeliverable ? DrainFilter::kPumpDeliverable : DrainFilter::kNestableV8; @@ -853,7 +848,7 @@ void EventLoop::WaitForInternalWork(int timeoutMs, bool pumpDeliverable) { } int EventLoop::EventFdCallback(int fd, int events, void* data) { - LooperCallbackScope callbackScope; + LooperCallbackScope callbackScope(static_cast(data)->looperCallbackDepth_); uint64_t value; // EFD_SEMAPHORE: consumes exactly one unit; while more remain the fd stays // readable and ALooper calls back next poll, interleaving with Java @@ -867,7 +862,7 @@ int EventLoop::EventFdCallback(int fd, int events, void* data) { } int EventLoop::TimerFdCallback(int fd, int events, void* data) { - LooperCallbackScope callbackScope; + LooperCallbackScope callbackScope(static_cast(data)->looperCallbackDepth_); uint64_t expirations; if (read(fd, &expirations, sizeof(expirations)) != sizeof(expirations)) { return 1; diff --git a/test-app/runtime/src/main/cpp/EventLoop.h b/test-app/runtime/src/main/cpp/EventLoop.h index f273bfe05..7c1b47298 100644 --- a/test-app/runtime/src/main/cpp/EventLoop.h +++ b/test-app/runtime/src/main/cpp/EventLoop.h @@ -191,15 +191,15 @@ class EventLoop { void RunNestableV8Tasks(); /** - * True while the calling thread is inside one of this process's ALooper - * fd callbacks. Android's Looper::pollInner holds a Response& into its - * response vector across each callback; a nested ALooper_pollOnce on the - * same looper clears and reallocates that vector, so the outer poll - * resumes over freed memory. Any code that pumps the looper (module + * True while this loop's home thread is inside one of the loop's ALooper + * fd callbacks; ask it only from the home thread. Android's + * Looper::pollInner holds a Response& into its response vector across + * each callback; a nested ALooper_pollOnce on the same looper clears and + * reallocates that vector, so the outer poll resumes over freed memory. Any code that pumps the looper (module * evaluation, the boot backstop, the fetch yield) must consult this and * drain queues directly instead of polling when it is set. */ - static bool IsInLooperCallback(); + bool IsInLooperCallback() const { return looperCallbackDepth_ > 0; } /** * Marks this loop's isolate as termination-requested. Callable from any @@ -419,6 +419,10 @@ class EventLoop { std::atomic claimCells_[kClaimCells] = {}; // Set by NoteTerminationRequested (any thread), read by PumpUntil. std::atomic_bool terminationRequested_{false}; + // Depth, not a flag: an fd callback can dispatch JS that lands back in + // another callback through a nested drain. Home thread only, like the fd + // callbacks that maintain it. + int looperCallbackDepth_ = 0; // ordered-lane source with its own bookkeeping (Timers); home-thread only OrderedTaskSource* timerSource_ = nullptr; // bare ordered tokens posted before the bind; flushed by Bind