From 672b82df3c7c0b481078335727db79dbfd338654 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oskar=20Kwas=CC=81niewski?= Date: Tue, 19 Dec 2023 10:09:49 -0800 Subject: [PATCH] feat: Optimise RCTKeyWindow() calls in RCTForceTouchAvailable method (#41935) Summary: This PR optimises RCTKeyWindow() calls in `RCTForceTouchAvailable` method. This method was calling RCTKeyWindow hundreds of times while scrolling on the screen. Before: On the video you can see that this function is being called **350 times** just from simple list scrolling. RCTKeyWindow is looping over app windows so it's not a cheap operation. https://github.com/facebook/react-native/assets/52801365/5b69cbd6-d148-4d06-b672-bd7b60472c13 After: the function is called only few times at the start of the app to get initial layout measurements. Solution: I think we can check just once for the force touch capabilities as devices can't change it on the fly bypass-github-export-checks ## Changelog: [IOS] [FIXED] - Optimise RCTKeyWindow() calls in RCTForceTouchAvailable method Pull Request resolved: https://github.com/facebook/react-native/pull/41935 Test Plan: CI Green Reviewed By: dmytrorykun Differential Revision: D52172510 Pulled By: cipolleschi fbshipit-source-id: 881a3125a2af4376ce65d785d8eee09c7d8f1f16 --- packages/react-native/React/Base/RCTUtils.m | 6 ++---- packages/react-native/React/UIUtils/RCTUIUtils.m | 3 +-- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/packages/react-native/React/Base/RCTUtils.m b/packages/react-native/React/Base/RCTUtils.m index 1fbabb7ca31af5..96bff171c827fb 100644 --- a/packages/react-native/React/Base/RCTUtils.m +++ b/packages/react-native/React/Base/RCTUtils.m @@ -634,12 +634,10 @@ BOOL RCTForceTouchAvailable(void) static BOOL forceSupported; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ - forceSupported = - [UITraitCollection class] && [UITraitCollection instancesRespondToSelector:@selector(forceTouchCapability)]; + forceSupported = [UITraitCollection currentTraitCollection].forceTouchCapability == UIForceTouchCapabilityAvailable; }); - return forceSupported && - (RCTKeyWindow() ?: [UIView new]).traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable; + return forceSupported; } #endif // [macOS] diff --git a/packages/react-native/React/UIUtils/RCTUIUtils.m b/packages/react-native/React/UIUtils/RCTUIUtils.m index 8d6ebc0ea5c2f4..c5fe036be9f593 100644 --- a/packages/react-native/React/UIUtils/RCTUIUtils.m +++ b/packages/react-native/React/UIUtils/RCTUIUtils.m @@ -15,8 +15,7 @@ RCTDimensions RCTGetDimensions(CGFloat fontScale) UIScreen *mainScreen = UIScreen.mainScreen; CGSize screenSize = mainScreen.bounds.size; - UIView *mainWindow; - mainWindow = RCTKeyWindow(); + UIView *mainWindow = RCTKeyWindow(); // We fallback to screen size if a key window is not found. CGSize windowSize = mainWindow ? mainWindow.bounds.size : screenSize; #else // [macOS