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

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...

16 AWS Gotchas

16 AWS Gotchas In January I launched the MVP for my own startup,  Proximistyle , which helps you find what you’re looking for nearby. On advice from friends and industry contacts I chose AWS as my cloud provider. Having never had to set up my own cloud infrastructure before, the learning curve to get from no experience to a stable VPC system I was happy with was significantly steeper than expected, and had its fair share of surprises. #1 Take advantage of the free resources offered AWS offers a free tier for new accounts. If you have recently bought a domain and set up a company you qualify for the free tier for a year. Additionally, if you are a bootstrapped startup you can apply for  the Startup Builders package  and get $1000 in AWS credits. After doing the above, you’re now ready to get started with setting up the AWS infrastructure for your startup. #2 Set up billing budgets and alerting The very first thing you should do after setting up billing, is enabling a budge...

Ultimate Folder Structure For Your React Native Project

  Ultimate Folder Structure For Your React Native Project React native project structure React Native is a flexible framework, giving developers the freedom to choose their code structure. However, this can be a double-edged sword for beginners. Though it offers ease of coding, it can soon become challenging to manage as your project expands. Thus, a structured folder system can be beneficial in many ways like better organization, simplified module management, adhering to coding practices, and giving a professional touch to your project. This write-up discusses a version of a folder arrangement that I employ in my React Native projects. This structure is based on best practices and can be modified to suit the specific needs of your project. Before we get into the project structure let’s give credit to @sanjay who has the original idea of the structure but I modify his version of the code, to make it better. Base library axios  — For network calling. react-navigation ...