From 14c207d9e1ffbfa8eeb3b2c6d2a6e334168a4d73 Mon Sep 17 00:00:00 2001 From: Vitalii T <44551710+Tabakharniuk@users.noreply.github.com> Date: Wed, 27 Jul 2022 06:57:21 -0700 Subject: [PATCH] Refactor: Minor performance improvement of BackHandler.removeEventListener (#34281) Summary: I've noticed that `BackHandler.removeEventListener()` performs two same `indexOf()` calls on an array that is not changing. By removing extra `indexOf` we can slightly improve time complexity of `BackHandler.removeEventListener()` from O(2n) to O(n) ## Changelog [Android] [Fixed] - Remove extra indexOf call in BackHandler.removeEventListener Pull Request resolved: https://github.com/facebook/react-native/pull/34281 Test Plan: 1. Add the following code to any function component ```javascript BackHandler.addEventListener('hardwareBackPress', () => true).remove(); ``` 2. Press on hardware back button Expected result: Application closes Reviewed By: dmitryrykun Differential Revision: D38198510 Pulled By: javache fbshipit-source-id: eab6a57689a536623138a4b3ebddbf9ba87d281f --- Libraries/Utilities/BackHandler.android.js | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/Libraries/Utilities/BackHandler.android.js b/Libraries/Utilities/BackHandler.android.js index 8162e8c7cd3..74519f78193 100644 --- a/Libraries/Utilities/BackHandler.android.js +++ b/Libraries/Utilities/BackHandler.android.js @@ -97,11 +97,9 @@ const BackHandler: TBackHandler = { eventName: BackPressEventName, handler: () => ?boolean, ): void { - if (_backPressSubscriptions.indexOf(handler) !== -1) { - _backPressSubscriptions.splice( - _backPressSubscriptions.indexOf(handler), - 1, - ); + const index = _backPressSubscriptions.indexOf(handler); + if (index !== -1) { + _backPressSubscriptions.splice(index, 1); } }, };