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

How I Reduced the Size of My React Native App by 85%

How and Why You Should Do It I borrowed 25$ from my friend to start a Play Store Developer account to put up my first app. I had already created the app, created the assets and published it in the store. Nobody wants to download a todo list app that costs 25mb of bandwidth and another 25 MB of storage space. So today I am going to share with you how I reduced the size of Tet from 25 MB to around 3.5 MB. Size Matters Like any beginner, I wrote my app using Expo, the awesome React Native platform that makes creating native apps a breeze. There is no native setup, you write javascript and Expo builds the binaries for you. I love everything about Expo except the size of the binaries. Each binary weighs around 25 MB regardless of your app. So the first thing I did was to migrate my existing Expo app to React Native. Migrating to React Native react-native init  a new project with the same name Copy the  source  files over from Expo project Install all de...

How to recover data of your Android KeyStore?

These methods can save you by recovering Key Alias and Key Password and KeyStore Password. This dialog becomes trouble to you? You should always keep the keystore file safe as you will not be able to update your previously uploaded APKs on PlayStore. It always need same keystore file for every version releases. But it’s even worse when you have KeyStore file and you forget any credentials shown in above box. But Good thing is you can recover them with certain tricks [Yes, there are always ways]. So let’s get straight to those ways. 1. Check your log files → For  windows  users, Go to windows file explorer C://Users/your PC name/.AndroidStudio1.4 ( your android studio version )\system\log\idea.log.1 ( or any old log number ) Open your log file in Notepad++ or Any text editor, and search for: android.injected.signing and if you are lucky enough then you will start seeing these. Pandroid.injected.signing.store.file = This is  file path where t...

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