From 8f5779cd70796ac65022919bee4c502ccfeec9ba Mon Sep 17 00:00:00 2001 From: Emily Janzer Date: Wed, 29 Jan 2020 11:43:22 -0800 Subject: [PATCH] Add in the optimization to check the first/least timer in the queue before iterating (#27841) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/27841 Follow up from https://github.com/facebook/react-native/pull/27539 - adding back in the optimization that Detox has in TimersIdlingResource to avoid iterating over the entire timers queue if the next timer is already within the specified range. Changelog: [Internal] Reviewed By: mdvacca Differential Revision: D19522346 fbshipit-source-id: 32609f434d1ca575a5a49ad630e288c43fa90864 --- .../react/modules/core/JavaTimerManager.java | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/core/JavaTimerManager.java b/ReactAndroid/src/main/java/com/facebook/react/modules/core/JavaTimerManager.java index 37548d4c46a..37fc90ff333 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/core/JavaTimerManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/core/JavaTimerManager.java @@ -384,12 +384,26 @@ public class JavaTimerManager { */ /* package */ boolean hasActiveTimersInRange(long rangeMs) { synchronized (mTimerGuard) { + Timer nextTimer = mTimers.peek(); + if (nextTimer == null) { + // Timers queue is empty + return false; + } + if (isTimerInRange(nextTimer, rangeMs)) { + // First check the next timer, so we can avoid iterating over the entire queue if it's + // already within range. + return true; + } for (Timer timer : mTimers) { - if (!timer.mRepeat && timer.mInterval < rangeMs) { + if (isTimerInRange(timer, rangeMs)) { return true; } } } return false; } + + private static boolean isTimerInRange(Timer timer, long rangeMs) { + return !timer.mRepeat && timer.mInterval < rangeMs; + } }