Skip to main content

Can React Native Close the Performance Gap? A Dive into C++ Turbo Native Modules

 

Can React Native Close the Performance Gap? A Dive into C++ Turbo Native Modules

Results

n=20  cpp=0ms    js=3ms
n=22 cpp=0ms js=4ms
n=25 cpp=1ms js=19ms
n=28 cpp=3ms js=75ms
n=30 cpp=6ms js=198ms
n=36 cpp=106ms js=3742ms
n=38 cpp=281ms js=9353ms
n=20  cpp=0ms    js=2ms
n=22 cpp=0ms js=7ms
n=25 cpp=3ms js=21ms
n=28 cpp=3ms js=84ms
n=30 cpp=7ms js=154ms
n=36 cpp=124ms js=2761ms
n=38 cpp=329ms js=7878ms

Skip the Setup and Implementation

cd CxxTurboModulesGuide
yarn install
cd ios && RCT_NEW_ARCH_ENABLED=1 bundle exec pod install && cd ..

Setup

npx react-native init CxxTurboModulesGuide
cd CxxTurboModulesGuide
yarn install
newArchEnabled=true
RCT_NEW_ARCH_ENABLED=1 bundle exec pod install

Turbo Module

1. JavaScript Specification

import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport';
import {TurboModuleRegistry} from 'react-native';

export interface Spec extends TurboModule {
readonly doFibExpensive: (n: number) => number;
}

export default TurboModuleRegistry.getEnforcing<Spec>('NativeSampleModule');

2. Codegen Configuration

Application

{
// ...
"description": "React Native with Cxx Turbo Native Modules",
"author": "<Evan Younan> <me@eyounan.com> (https://github.com/e-younan)",
"license": "MIT",
"homepage": "https://github.com/e-younan/#readme",
// ...
"codegenConfig": {
"name": "AppSpecs",
"type": "all",
"jsSrcsDir": "tm",
"android": {
"javaPackageName": "com.facebook.fbreact.specs"
}
}
}

iOS: Create the podspec file

require "json"

package = JSON.parse(File.read(File.join(__dir__, "../package.json")))

Pod::Spec.new do |s|
s.name = "AppTurboModules"
s.version = package["version"]
s.summary = package["description"]
s.description = package["description"]
s.homepage = package["homepage"]
s.license = package["license"]
s.platforms = { :ios => "12.4" }
s.author = package["author"]
s.source = { :git => package["repository"], :tag => "#{s.version}" }
s.source_files = "**/*.{h,cpp}"
s.pod_target_xcconfig = {
"CLANG_CXX_LANGUAGE_STANDARD" => "c++17"
}
install_modules_dependencies(s)
end
  # ...

use_react_native!(
:path => config[:reactNativePath],
# Hermes is now enabled by default. Disable by setting this flag to false.
# Upcoming versions of React Native may rely on get_default_flags(), but
# we make it explicit here to aid in the React Native upgrade process.
:hermes_enabled => flags[:hermes_enabled],
:fabric_enabled => flags[:fabric_enabled],
# Enables Flipper.
#
# Note that if you have use_frameworks! enabled, Flipper will not work and
# you should disable the next line.
:flipper_configuration => flipper_config,
# An absolute path to your application root.
:app_path => "#{Pod::Config.instance.installation_root}/.."
)

target 'CxxTurboModulesGuideTests' do
inherit! :complete
# Pods for testing
end

# To register our Turbo Module
if ENV['RCT_NEW_ARCH_ENABLED'] == '1'
pod 'AppTurboModules', :path => "./../tm"
end

# ...

Android: build.gradleCMakeLists.txtOnload.cpp

cmake_minimum_required(VERSION 3.13)
set(CMAKE_VERBOSE_MAKEFILE on)

add_compile_options(
-fexceptions
-frtti
-std=c++17)

file(GLOB tm_SRC CONFIGURE_DEPENDS *.cpp)
add_library(tm STATIC ${tm_SRC})

target_include_directories(tm PUBLIC .)
target_include_directories(react_codegen_AppSpecs PUBLIC .)

target_link_libraries(tm
jsi
react_nativemodule_core
react_codegen_AppSpecs)
android {
// ...

// Add this block
externalNativeBuild {
cmake {
path "src/main/jni/CMakeLists.txt"
}
}

// ...
}

3. Module Registration

iOS

#import "AppDelegate.h"

#import <React/RCTBundleURLProvider.h>
#import <React/CoreModulesPlugins.h>
#import <ReactCommon/RCTTurboModuleManager.h>
#import <NativeSampleModule.h>

@interface AppDelegate () <RCTTurboModuleManagerDelegate> {}
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.moduleName = @"CxxTurboModulesGuide";
// You can add your custom initial props in the dictionary below.
// They will be passed down to the ViewController used by React Native.
self.initialProps = @{};

return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"];
#else
return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}

/// This method controls whether the `concurrentRoot`feature of React18 is turned on or off.
///
/// @see: https://reactjs.org/blog/2022/03/29/react-v18.html
/// @note: This requires to be rendering on Fabric (i.e. on the New Architecture).
/// @return: `true` if the `concurrentRoot` feature is enabled. Otherwise, it returns `false`.
- (BOOL)concurrentRootEnabled
{
return true;
}

#pragma mark RCTTurboModuleManagerDelegate

- (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:(const std::string &)name
jsInvoker:(std::shared_ptr<facebook::react::CallInvoker>)jsInvoker
{
if (name == "NativeSampleModule") {
return std::make_shared<facebook::react::NativeSampleModule>(jsInvoker);
}
return nullptr;
}

@end

Android

cd android/app/src/main
mkdir jni
cd ../../../..
cp node_modules/react-native/ReactAndroid/cmake-utils/default-app-setup/CMakeLists.txt android/app/src/main/jni/
cp node_modules/react-native/ReactAndroid/cmake-utils/default-app-setup/OnLoad.cpp android/app/src/main/jni/
// ...

#include <react/renderer/componentregistry/ComponentDescriptorProviderRegistry.h>
#include <rncli.h>
+ #include <NativeSampleModule.h>

// ...

std::shared_ptr<TurboModule> cxxModuleProvider(
const std::string &name,
const std::shared_ptr<CallInvoker> &jsInvoker)
{
+ if (name == "NativeSampleModule") {
+ return std::make_shared<facebook::react::NativeSampleModule>(jsInvoker);
+ }
return nullptr;
}

// ...
// ...

# This file includes all the necessary to let you build your application with the New Architecture.
include(${REACT_ANDROID_DIR}/cmake-utils/ReactNative-application.cmake)

+ # App needs to add and link against tm (TurboModules) folder
+ add_subdirectory(${REACT_ANDROID_DIR}/../../../tm/ tm_build)
+ target_link_libraries(${CMAKE_PROJECT_NAME} tm)

4. C++ Native Code

RCT_NEW_ARCH_ENABLED=1 bundle exec pod install
yarn android

Implementation

#pragma once

#if __has_include(<React-Codegen/AppSpecsJSI.h>) // CocoaPod headers on Apple
#include <React-Codegen/AppSpecsJSI.h>
#elif __has_include("AppSpecsJSI.h") // CMake headers on Android
#include "AppSpecsJSI.h"
#endif
#include <memory>
#include <string>

namespace facebook::react
{

class NativeSampleModule : public NativeSampleModuleCxxSpec<NativeSampleModule>
{
public:
NativeSampleModule(std::shared_ptr<CallInvoker> jsInvoker);

int doFibExpensive(jsi::Runtime &rt, int n);
};

} // namespace facebook::react
#include <fstream>
#include "NativeSampleModule.h"

namespace facebook::react
{

NativeSampleModule::NativeSampleModule(std::shared_ptr<CallInvoker> jsInvoker)
: NativeSampleModuleCxxSpec(std::move(jsInvoker)) {}

int NativeSampleModule::doFibExpensive(jsi::Runtime &rt, int n)
{
if (n < 2)
{
return n;
}
else
{
return doFibExpensive(rt, n - 1) + doFibExpensive(rt, n - 2);
}
}
} // namespace facebook::react
RCT_NEW_ARCH_ENABLED=1 bundle exec pod install

5. Adding the C++ Turbo Native Module to the App

import React, {useState} from 'react';
import {
SafeAreaView,
Text,
StyleSheet,
View,
ScrollView,
Button,
} from 'react-native';
import NativeSampleModule from './tm/NativeSampleModule';

const TESTS = [20, 22, 25, 28, 30, 36, 38];

const doJsFib = (n: number): number => {
if (n < 2) {
return n;
}
return doJsFib(n - 1) + doJsFib(n - 2);
};

const doFibTest = async (n: number) => {
// Wait 100ms before starting the test to allow the app to settle and render new results
await new Promise(res => setTimeout(() => res(null), 100));

let before = Date.now();
// C++
NativeSampleModule.doFibExpensive(n);
const duration = Date.now() - before;

before = Date.now();
// JS
doJsFib(n);
const duration2 = Date.now() - before;

return [duration, duration2] as const;
};

interface FibonacciTestResult {
n: number;
cppDuration: number;
jsDuration: number;
}

export default function App(): JSX.Element {
const [running, setRunning] = useState(false);
// Store the results of the tests
const [results, setResults] = useState<FibonacciTestResult[]>([]);

const onPressStart = async () => {
if (running) {
return;
}

setRunning(true);

for await (const n of TESTS) {
const [cppDuration, jsDuration] = await doFibTest(n);
setResults(prev => [...prev, {n, cppDuration, jsDuration}]);
}

setRunning(false);
};

return (
<SafeAreaView style={styles.container}>
<ScrollView style={styles.scrollStyle}>
<Text style={styles.title}>C++ vs JS Fibonacci Test</Text>
<Button
disabled={running}
title={running ? 'Running - please wait...' : 'Start test'}
onPress={onPressStart}
/>

<View style={styles.titleRow}>
<Text style={styles.boldText}>n</Text>
<Text style={styles.boldText}>C++</Text>
<Text style={styles.boldText}>JS</Text>
</View>

<View style={styles.resultsContainer}>
{results.map((test, i) => (
<View style={styles.resultRow} key={`test-${i}`}>
<Text style={styles.text}>{test.n}</Text>
<Text style={styles.text}>{test.cppDuration}ms</Text>
<Text style={styles.text}>{test.jsDuration}ms</Text>
</View>
))}
</View>
</ScrollView>
</SafeAreaView>
);
}

const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'white',
},
scrollStyle: {
flex: 1,
},
button: {
backgroundColor: 'lightblue',
padding: 10,
justifyContent: 'center',
alignItems: 'center',
},
resultsContainer: {
marginTop: 20,
gap: 8,
},
titleRow: {
marginTop: 20,
width: '100%',
alignItems: 'center',
flexDirection: 'row',
},
resultRow: {
width: '100%',
alignItems: 'center',
flexDirection: 'row',
},
text: {
flex: 1,
textAlign: 'center',
},
boldText: {
flex: 1,
fontWeight: 'bold',
textAlign: 'center',
},
title: {
fontSize: 20,
fontWeight: 'bold',
marginVertical: 12,
textAlign: 'center',
},
});

Conclusion

Comments

Popular Posts

Reloading UITableView while Animating Scroll in iOS 11

Reloading UITableView while Animating Scroll Calling  reloadData  on  UITableView  may not be the most efficient way to update your cells, but sometimes it’s easier to ensure the data you are storing is in sync with what your  UITableView  is showing. In iOS 10  reloadData  could be called at any time and it would not affect the scrolling UI of  UITableView . However, in iOS 11 calling  reloadData  while your  UITableView  is animating scrolling causes the  UITableView  to stop its scroll animation and not complete. We noticed this is only true for scroll animations triggered via one of the  UITableView  methods (such as  scrollToRow(at:at:animated:) ) and not for scroll animations caused by user interaction. This can be an issue when server responses trigger a  reloadData  call since they can happen at any moment, possibly when scroll animation is occurring. Example of s...

What are the Alternatives of device UDID in iOS? - iOS7 / iOS 6 / iOS 5 – Get Device Unique Identifier UDID

Get Device Unique Identifier UDID Following code will help you to get the unique-device-identifier known as UDID. No matter what iOS user is using, you can get the UDID of the current iOS device by following code. - ( NSString *)UDID { NSString *uuidString = nil ; // get os version NSUInteger currentOSVersion = [[[[[UIDevice currentDevice ] systemVersion ] componentsSeparatedByString: @" . " ] objectAtIndex: 0 ] integerValue ]; if (currentOSVersion <= 5 ) { if ([[ NSUserDefaults standardUserDefaults ] valueForKey: @" udid " ]) { uuidString = [[ NSUserDefaults standardDefaults ] valueForKey: @" udid " ]; } else { CFUUIDRef uuidRef = CFUUIDCreate ( kCFAllocatorDefault ); uuidString = ( NSString *) CFBridgingRelease ( CFUUIDCreateString ( NULL ,uuidRef)); CFRelease (uuidRef); [[ NSUserDefaults standardUserDefaults ] setObject: uuidString ForKey: @" udid " ]; [[ NSUserDefaults standardUserDefaults ] synchro...

Xcode & Instruments: Measuring Launch time, CPU Usage, Memory Leaks, Energy Impact and Frame Rate

When you’re developing applications for modern mobile devices, it’s vital that you consider the performance footprint that it has on older devices and in less than ideal network conditions. Fortunately Apple provides several powerful tools that enable Engineers to measure, investigate and understand the different performance characteristics of an application running on an iOS device. Recently I spent some time with these tools working to better understand the performance characteristics of an eCommerce application and finding ways that we can optimise the experience for our users. We realised that applications that are increasingly performance intensive, consume excessive amounts of memory, drain battery life and feel uncomfortably slow are less likely to retain users. With the release of iOS 12.0 it’s easier than ever for users to find applications that are consuming the most of their device’s finite amount of resources. Users can now make informed decisions abou...