mirror of
https://github.com/facebook/react-native.git
synced 2026-11-18 20:19:07 +00:00
Look up each TurboModule method's signature once on iOS (#59394)
Summary: On iOS, every call from JavaScript to an Objective-C TurboModule method goes through `ObjCTurboModule::createMethodInvocation` (`ReactCommon/react/nativemodule/core/platform/ios/ReactCommon/RCTTurboModule.mm`), which asks the module for the method's signature with `methodSignatureForSelector:`. For methods declared in a protocol, the runtime looks the selector up in the module's protocol list (`class_copyProtocolList`, `protocol_getMethodDescription`) and builds a new `NSMethodSignature` each time. In a Time Profiler trace of a loop of sync calls on an iPhone 15 Pro, this lookup was about 25% of `invokeObjCMethod`. A method's signature doesn't change, so this change looks it up on the method's first call and keeps it. Each `ObjCTurboModule` now has one `MethodInfo` struct per method, keyed by the method's JS name, which holds the signature together with the metadata that was already kept per method: the argument types from `RCT_EXPORT_METHOD` and the `RCTCxxConvert` selectors set by the generated code. This replaces `methodArgConversionSelectors_` and `methodArgumentTypeNames_`, two dictionaries keyed by an `NSString` method name. The map is looked up with a `std::string_view`, so no string is allocated on a call. The cache is per instance and still calls `methodSignatureForSelector:` on the module instance, so it keeps the behavior from https://github.com/react/react-native/issues/51366: a mock module is a different instance and gets its own cache. A mutex guards the map. The members are private, so there is no API change. Memory: one entry per method that is actually called. Running RNTester's TurboModule, Linking, AppState, Clipboard, Vibration, Share and Alert examples filled 40 entries across 12 modules. An `NSMethodSignature` for a method with 4–6 arguments takes about 620 bytes, so this is about 25 KB. The signatures were already created on every call and released right after. ## Changelog: [IOS] [CHANGED] - Look up each TurboModule method's signature once instead of on every call Pull Request resolved: https://github.com/react/react-native/pull/59394 Test Plan: - `clang-format --dry-run --Werror` (the repository's pinned version) on the changed files passes. - I could not run `RNTesterUnitTests` locally: with Xcode 26.3 the test build fails to link `RNTesterIntegrationTests` (`__swift_FORCE_LOAD_$_swiftCompatibility56` not found), which is unrelated to this change. `RCTTurboModuleArrayBufferTests` calls `invokeObjCMethod` directly, so I'm relying on CI for it; the same paths are covered by the TurboModule example below. - RNTester built with `xcodebuild` in Release and run on a physical iPhone 15 Pro (iOS 26.6.1). In the TurboModule example, "Run function call tests" returns the expected value for all 18 methods, including callbacks, a resolved and a rejected promise, and ArrayBuffers. The Alert example, whose `alertWithArgs` argument goes through an `RCTCxxConvert` selector, shows its alerts as before. - **Measurement.** RNTester Playground calling `NativeSampleTurboModule` methods in a loop (20,000 calls each for the sync methods, 5,000 for `voidFunc` and `getValueWithCallback`), measured with `performance.now()`. Two Release builds, before and after this change, installed in the order before, after, after, before, 4 launches each. The presses were driven by [Argent](https://github.com/software-mansion/argent) on the physical iPhone. Mean time per call: | Call | before | this PR | change | |---|--:|--:|--:| | `getNumber` | 2.85 µs | 2.25 µs | −21% | | `getBool` | 1.46 µs | 1.19 µs | −18% | | `getString` | 1.56 µs | 1.31 µs | −16% | | `getArray` (3 items) | 1.93 µs | 1.65 µs | −14% | | `getObject` (small) | 2.75 µs | 2.53 µs | −8% | | `getObject` (20 keys) | 11.08 µs | 10.81 µs | −2% | | `getValue` | 2.97 µs | 2.81 µs | −6% | | `voidFunc` (async) | 1.04 µs | 0.60 µs | −42% | | `getValueWithCallback` | 1.51 µs | 0.98 µs | −35% | For every row except `getNumber`, the ranges of the two arms don't overlap. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Reviewed By: andrewdacenko Differential Revision: D127179102 Pulled By: javache fbshipit-source-id: beb48cb385af0719f2d37040c1fbcd7dbfc0fd4c
This commit is contained in:
1 parent
ca952774d6
commit
1d1fade902
2 files changed
+79
-50
No files matched your search
+24
-8
@@ -16,8 +16,11 @@
|
||||
#import <React/RCTModuleMethod.h>
|
||||
#import <functional>
|
||||
#import <memory>
|
||||
#import <mutex>
|
||||
#import <string>
|
||||
#import <string_view>
|
||||
#import <unordered_map>
|
||||
#import <vector>
|
||||
|
||||
#define RCT_IS_TURBO_MODULE_CLASS(klass) \
|
||||
((RCTTurboModuleEnabled() && [(klass) conformsToProtocol:@protocol(RCTTurboModule)]))
|
||||
@@ -132,14 +135,27 @@ class JSI_EXPORT ObjCTurboModule : public TurboModule {
|
||||
// Does the NativeModule dispatch async methods to the JS thread?
|
||||
const bool isSyncModule_;
|
||||
|
||||
/**
|
||||
* TODO(ramanpreet):
|
||||
* Investigate an optimization that'll let us get rid of this NSMutableDictionary.
|
||||
* Perhaps, have the code-generated TurboModule subclass implement
|
||||
* getMethodArgConversionSelector below.
|
||||
*/
|
||||
NSMutableDictionary<NSString *, NSMutableArray *> *methodArgConversionSelectors_;
|
||||
NSDictionary<NSString *, NSArray<NSString *> *> *methodArgumentTypeNames_;
|
||||
struct MethodInfo {
|
||||
// Looked up on the method's first call, since it doesn't change.
|
||||
NSMethodSignature *signature;
|
||||
// Argument types declared with RCT_EXPORT_METHOD, used to convert arguments with RCTConvert.
|
||||
NSArray<NSString *> *argumentTypeNames;
|
||||
// RCTCxxConvert selectors that convert arguments to C++ structs, set by the generated code.
|
||||
std::vector<SEL> argConversionSelectors;
|
||||
};
|
||||
struct MethodNameHash {
|
||||
using is_transparent = void;
|
||||
size_t operator()(std::string_view methodName) const
|
||||
{
|
||||
return std::hash<std::string_view>{}(methodName);
|
||||
}
|
||||
};
|
||||
// Keyed by the method's JS name; looked up without allocating a std::string.
|
||||
std::unordered_map<std::string, MethodInfo, MethodNameHash, std::equal_to<>> methodInfos_;
|
||||
bool argumentTypeNamesLoaded_{false};
|
||||
std::mutex methodInfosMutex_;
|
||||
MethodInfo &findOrCreateMethodInfo(std::string_view methodName);
|
||||
NSMethodSignature *getMethodSignature(const char *methodName, SEL selector);
|
||||
|
||||
bool isMethodSync(TurboModuleMethodValueKind returnType);
|
||||
bool mustCopyJSHeapArrayBufferBytes(TurboModuleMethodValueKind returnType);
|
||||
|
||||
+55
-42
@@ -680,9 +680,8 @@ jsi::Value ObjCTurboModule::convertReturnIdToJSIValue(
|
||||
*/
|
||||
NSString *ObjCTurboModule::getArgumentTypeName(jsi::Runtime &runtime, NSString *methodName, int argIndex)
|
||||
{
|
||||
if (methodArgumentTypeNames_ == nullptr) {
|
||||
NSMutableDictionary<NSString *, NSArray<NSString *> *> *methodArgumentTypeNames = [NSMutableDictionary new];
|
||||
|
||||
std::lock_guard<std::mutex> lock(methodInfosMutex_);
|
||||
if (!argumentTypeNamesLoaded_) {
|
||||
unsigned int numberOfMethods;
|
||||
Class cls = [instance_ class];
|
||||
Method *methods = class_copyMethodList(object_getClass(cls), &numberOfMethods);
|
||||
@@ -707,19 +706,21 @@ NSString *ObjCTurboModule::getArgumentTypeName(jsi::Runtime &runtime, NSString *
|
||||
[argumentTypes addObject:arguments[j].type];
|
||||
}
|
||||
|
||||
NSString *normalizedOtherMethodName = [otherMethodName componentsSeparatedByString:@":"][0];
|
||||
methodArgumentTypeNames[normalizedOtherMethodName] = argumentTypes;
|
||||
std::string_view otherMethodNameView = otherMethodName.UTF8String;
|
||||
std::string_view normalizedOtherMethodName = otherMethodNameView.substr(0, otherMethodNameView.find(':'));
|
||||
findOrCreateMethodInfo(normalizedOtherMethodName).argumentTypeNames = argumentTypes;
|
||||
}
|
||||
|
||||
free(methods);
|
||||
}
|
||||
|
||||
methodArgumentTypeNames_ = methodArgumentTypeNames;
|
||||
argumentTypeNamesLoaded_ = true;
|
||||
}
|
||||
|
||||
if (methodArgumentTypeNames_[methodName] != nullptr) {
|
||||
assert([methodArgumentTypeNames_[methodName] count] > argIndex);
|
||||
return methodArgumentTypeNames_[methodName][argIndex];
|
||||
auto it = methodInfos_.find(std::string_view(methodName.UTF8String));
|
||||
if (it != methodInfos_.end() && it->second.argumentTypeNames != nil) {
|
||||
assert([it->second.argumentTypeNames count] > argIndex);
|
||||
return it->second.argumentTypeNames[argIndex];
|
||||
}
|
||||
|
||||
return nil;
|
||||
@@ -818,18 +819,19 @@ void ObjCTurboModule::setInvocationArg(
|
||||
/**
|
||||
* Convert objects using RCTCxxConvert to structs.
|
||||
*/
|
||||
if ([objCArg isKindOfClass:[NSDictionary class]] && hasMethodArgConversionSelector(methodNameNSString, i)) {
|
||||
if ([objCArg isKindOfClass:[NSDictionary class]]) {
|
||||
SEL methodArgConversionSelector = getMethodArgConversionSelector(methodNameNSString, i);
|
||||
if (methodArgConversionSelector != nullptr) {
|
||||
// Message dispatch logic from old infra (link:
|
||||
// https://github.com/facebook/react-native/commit/6783694158057662fd7b11fc123c339b2b21bfe6#diff-263fc157dfce55895cdc16495b55d190R350)
|
||||
RCTManagedPointer *(*convert)(id, SEL, id) = (__typeof__(convert))objc_msgSend;
|
||||
RCTManagedPointer *box = convert([RCTCxxConvert class], methodArgConversionSelector, objCArg);
|
||||
|
||||
// Message dispatch logic from old infra (link:
|
||||
// https://github.com/facebook/react-native/commit/6783694158057662fd7b11fc123c339b2b21bfe6#diff-263fc157dfce55895cdc16495b55d190R350)
|
||||
RCTManagedPointer *(*convert)(id, SEL, id) = (__typeof__(convert))objc_msgSend;
|
||||
RCTManagedPointer *box = convert([RCTCxxConvert class], methodArgConversionSelector, objCArg);
|
||||
|
||||
void *pointer = box.voidPointer;
|
||||
[inv setArgument:&pointer atIndex:i + 2];
|
||||
[retainedObjectsForInvocation addObject:box];
|
||||
return;
|
||||
void *pointer = box.voidPointer;
|
||||
[inv setArgument:&pointer atIndex:i + 2];
|
||||
[retainedObjectsForInvocation addObject:box];
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -842,6 +844,26 @@ void ObjCTurboModule::setInvocationArg(
|
||||
}
|
||||
}
|
||||
|
||||
ObjCTurboModule::MethodInfo &ObjCTurboModule::findOrCreateMethodInfo(std::string_view methodName)
|
||||
{
|
||||
auto it = methodInfos_.find(methodName);
|
||||
if (it == methodInfos_.end()) {
|
||||
it = methodInfos_.emplace(std::string(methodName), MethodInfo{}).first;
|
||||
}
|
||||
return it->second;
|
||||
}
|
||||
|
||||
NSMethodSignature *ObjCTurboModule::getMethodSignature(const char *methodName, SEL selector)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(methodInfosMutex_);
|
||||
MethodInfo &methodInfo = findOrCreateMethodInfo(methodName);
|
||||
if (methodInfo.signature == nil) {
|
||||
const NSObject<RCTBridgeModule> *module = instance_;
|
||||
methodInfo.signature = [module methodSignatureForSelector:selector];
|
||||
}
|
||||
return methodInfo.signature;
|
||||
}
|
||||
|
||||
NSInvocation *ObjCTurboModule::createMethodInvocation(
|
||||
jsi::Runtime &runtime,
|
||||
bool isSync,
|
||||
@@ -859,8 +881,7 @@ NSInvocation *ObjCTurboModule::createMethodInvocation(
|
||||
TurboModulePerfLogger::asyncMethodCallArgConversionStart(moduleName, methodName);
|
||||
}
|
||||
|
||||
const NSObject<RCTBridgeModule> *module = instance_;
|
||||
NSMethodSignature *methodSignature = [module methodSignatureForSelector:selector];
|
||||
NSMethodSignature *methodSignature = getMethodSignature(methodName, selector);
|
||||
if (count > methodSignature.numberOfArguments - 2) {
|
||||
throw jsi::JSError(
|
||||
runtime,
|
||||
@@ -986,36 +1007,28 @@ jsi::Value ObjCTurboModule::invokeObjCMethod(
|
||||
|
||||
BOOL ObjCTurboModule::hasMethodArgConversionSelector(NSString *methodName, size_t argIndex)
|
||||
{
|
||||
return (methodArgConversionSelectors_ != nullptr) && (methodArgConversionSelectors_[methodName] != nullptr) &&
|
||||
![methodArgConversionSelectors_[methodName][argIndex] isEqual:(id)kCFNull];
|
||||
return getMethodArgConversionSelector(methodName, argIndex) != nullptr;
|
||||
}
|
||||
|
||||
SEL ObjCTurboModule::getMethodArgConversionSelector(NSString *methodName, size_t argIndex)
|
||||
{
|
||||
assert(hasMethodArgConversionSelector(methodName, argIndex));
|
||||
return (SEL)((NSValue *)methodArgConversionSelectors_[methodName][argIndex]).pointerValue;
|
||||
std::lock_guard<std::mutex> lock(methodInfosMutex_);
|
||||
auto it = methodInfos_.find(std::string_view(methodName.UTF8String));
|
||||
if (it == methodInfos_.end() || argIndex >= it->second.argConversionSelectors.size()) {
|
||||
return nullptr;
|
||||
}
|
||||
return it->second.argConversionSelectors[argIndex];
|
||||
}
|
||||
|
||||
void ObjCTurboModule::setMethodArgConversionSelector(NSString *methodName, size_t argIndex, NSString *fnName)
|
||||
{
|
||||
if (methodArgConversionSelectors_ == nullptr) {
|
||||
methodArgConversionSelectors_ = [NSMutableDictionary new];
|
||||
const char *methodNameUTF8 = methodName.UTF8String;
|
||||
std::lock_guard<std::mutex> lock(methodInfosMutex_);
|
||||
std::vector<SEL> &selectors = findOrCreateMethodInfo(methodNameUTF8).argConversionSelectors;
|
||||
if (selectors.empty()) {
|
||||
selectors.resize(methodMap_.at(methodNameUTF8).argCount, nullptr);
|
||||
}
|
||||
|
||||
if (methodArgConversionSelectors_[methodName] == nullptr) {
|
||||
auto metaData = methodMap_.at([methodName UTF8String]);
|
||||
auto argCount = metaData.argCount;
|
||||
|
||||
methodArgConversionSelectors_[methodName] = [NSMutableArray arrayWithCapacity:argCount];
|
||||
for (int i = 0; i < argCount; i += 1) {
|
||||
[methodArgConversionSelectors_[methodName] addObject:(id)kCFNull];
|
||||
}
|
||||
}
|
||||
|
||||
SEL selector = NSSelectorFromString(fnName);
|
||||
NSValue *selectorValue = [NSValue valueWithPointer:selector];
|
||||
|
||||
methodArgConversionSelectors_[methodName][argIndex] = selectorValue;
|
||||
selectors.at(argIndex) = NSSelectorFromString(fnName);
|
||||
}
|
||||
|
||||
void ObjCTurboModule::setEventEmitterCallback(EventEmitterCallback eventEmitterCallback)
|
||||
|
||||
Reference in new issue
Block a user