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

React Native - Text Input

In this chapter, we will show you how to work with  TextInput  elements in React Native. The Home component will import and render inputs. App.js import React from 'react' ; import Inputs from './inputs.js' const App = () => { return ( < Inputs /> ) } export default App Inputs We will define the initial state. After defining the initial state, we will create the  handleEmail  and the  handlePassword  functions. These functions are used for updating state. The  login()  function will just alert the current value of the state. We will also add some other properties to text inputs to disable auto capitalisation, remove the bottom border on Android devices and set a placeholder. inputs.js import React , { Component } from 'react' import { View , Text , TouchableOpacity , TextInput , StyleSheet } from 'react-native' class Inputs extends Component { state = { ...

An introduction to Size Classes for Xcode 8

Introduction to Size Classes for Xcode In iOS 8, Apple introduced  size classes , a way to describe any device in any orientation. Size classes rely heavily on auto layout. Until iOS 8, you could escape auto layout. IN iOS8, Apple changed several UIKit classes to depend on size classes. Modal views, popovers, split views, and image assets directly use size classes to determine how to display an image. Identical code to present a popover on an iPad  causes a iPhone to present a modal view. Different Size Classes There are two sizes for size classes:  compact , and  regular . Sometime you’ll hear about any.  Any  is the generic size that works with anything. The default Xcode layout, is  width:any height:any . This layout is for all cases. The Horizontal and vertical dimensions are called  traits , and can be accessed in code from an instance of  UITraitCollection . The  compact  size descr...

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