diff --git a/docs/backlog.md b/docs/backlog.md index 5fb42fc..d1ded7f 100644 --- a/docs/backlog.md +++ b/docs/backlog.md @@ -65,24 +65,23 @@ list; the other four worked. Check it again before treating it as a bug. None of these grows memory over time: they cost CPU and short-lived garbage. -### The indicator reads shared values synchronously on every scroll frame - -[FastScrollIndicator.tsx:250-256](../src/FastScrollIndicator/FastScrollIndicator.tsx#L250-L256): -`onScrollToOffsetPercentage` reads `disableOnScrollEvent.value` and -`viewLayout.value` on the JS thread. On Reanimated 3 (native), reading `.value` -from JS goes through `executeOnUIRuntimeSync` (`react-native-reanimated` -`src/mutables.ts`): the JS thread blocks until the UI runtime answers. That -happens twice per scroll frame, while the UI runtime is busy with the scroll. -On Reanimated 2.12, which this repo develops against, the read is cheap, so -tests do not show it. - -Possible fix: keep JS mirrors in refs (height from `onLayout`, a dragging flag -set with `runOnJS` from `onBegin` / `onFinalize`), or move the whole update into -one asynchronous `runOnUI` call. - -`FastScrollSectionDotsBar`'s handle does the same -([FastScrollSectionDotsBar.tsx:266-271](../src/FastScrollSectionDots/FastScrollSectionDotsBar.tsx#L266-L271)), -but it is called on viewability changes, not on every frame. +### The dots bar reads shared values synchronously on viewability changes + +[FastScrollSectionDotsBar.tsx:266-271](../src/FastScrollSectionDots/FastScrollSectionDotsBar.tsx#L266-L271): +the bar's `onSectionChange` handle, reached from `onViewableIndexChanged`, reads +`enableExternalScrollEvents.value` and `containerScrollY.value` on the JS +thread. On Reanimated 3 (native), reading `.value` from JS goes through +`executeOnUIRuntimeSync` (`react-native-reanimated` `src/mutables.ts`), which +takes the UI runtime's lock and runs the read on the JS thread: the JS thread +waits while the UI thread runs worklets. On the example's IndicatorCost screen, +two such reads during a scroll took 0.44-0.79 ms at the median and 12-17 ms at +p95 (Android emulator, production bundle). On Reanimated 2.12, which this repo +develops against, the read is cheap, so tests do not show it. + +It runs on viewability changes, not on every frame, so it costs far less than +the same reads did in `FastScrollIndicator`, which now keeps JS copies (the +track height from `onLayout`, a finger-on-track flag set with `runOnJS` from +the pan's `onBegin` / `onFinalize`). The same approach applies here. ### Dragging the dots does work on every frame, even without a section change diff --git a/example/src/ExamplesScreen.tsx b/example/src/ExamplesScreen.tsx index fdda281..3bc588f 100644 --- a/example/src/ExamplesScreen.tsx +++ b/example/src/ExamplesScreen.tsx @@ -26,6 +26,7 @@ export const ExamplesScreen = () => { { title: 'DotsLayout', destination: 'DotsLayout' }, { title: 'MemoryLeak', destination: 'MemoryLeak' }, { title: 'ReplaceSections', destination: 'ReplaceSections' }, + { title: 'IndicatorCost', destination: 'IndicatorCost' }, ]; return ( <> diff --git a/example/src/NavigationTree.tsx b/example/src/NavigationTree.tsx index f618b24..0646098 100644 --- a/example/src/NavigationTree.tsx +++ b/example/src/NavigationTree.tsx @@ -10,6 +10,7 @@ import StaleCallback from './staleCallback/StaleCallback'; import DotsLayout from './dotsLayout/DotsLayout'; import MemoryLeak from './memoryLeak/MemoryLeak'; import ReplaceSections from './replaceSections/ReplaceSections'; +import IndicatorCost from './indicatorCost/IndicatorCost'; const Stack = createStackNavigator(); @@ -25,6 +26,7 @@ const NavigationTree = () => { + diff --git a/example/src/indicatorCost/IndicatorCost.tsx b/example/src/indicatorCost/IndicatorCost.tsx new file mode 100644 index 0000000..4638ee5 --- /dev/null +++ b/example/src/indicatorCost/IndicatorCost.tsx @@ -0,0 +1,217 @@ +import React, { useCallback, useEffect, useRef, useState } from 'react'; +import { + NativeScrollEvent, + NativeSyntheticEvent, + Pressable, + StyleSheet, + Text, + View, +} from 'react-native'; +import { FlashList } from '@shopify/flash-list'; +import { useSharedValue } from 'react-native-reanimated'; +import { FastScrollIndicator } from 'react-native-fast-scroll'; + +/** + * Times `FastScrollIndicator`'s `onScrollToOffsetPercentage` on the JS thread, + * the handle apps call on every scroll frame. On Reanimated 3, reading a + * shared value from JS takes the UI runtime's lock, so it waits whenever the + * UI thread is running worklets, as it does while the list scrolls and the + * indicator animates. Measure with a production bundle + * (`expo start --no-dev --minify`) and clear Expo Go's data between versions: + * it keeps reusing a cached production bundle. + * + * - "Loop": calls the handle 1000 times in a row and reports the time per + * call. + * - Scrolling the list: every `onScroll` frame calls the handle, as an app + * does, and times that call alone. "Scroll stats" reports them; "Reset" + * clears them. + * - "Reads": in the same frames, right after the handle, the time of two + * reads from JS of shared values shaped like the ones the indicator's + * handle read before it kept JS copies (a flag and a layout object). It + * shows what those two reads cost under the same load, frame by frame, + * whatever version of the indicator the example runs. + * + * Also driven from the debugger through `global.__indicatorCost` + * (`loop(n)`, `scrollStats()`, `reset()`), which return the same numbers. + */ + +const ROWS = Array.from({ length: 2000 }, (_, i) => i); +const ROW_HEIGHT = 44; +const LOOP_CALLS = 1000; + +type Stats = { + calls: number; + meanUs: number; + p50Us: number; + p95Us: number; + maxUs: number; +}; + +const toStats = (durationsMs: number[]): Stats => { + const sorted = [...durationsMs].sort((a, b) => a - b); + const at = (q: number) => + sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))] ?? 0; + const sum = sorted.reduce((total, ms) => total + ms, 0); + const us = (ms: number) => Math.round(ms * 1000); + return { + calls: sorted.length, + meanUs: us(sorted.length ? sum / sorted.length : 0), + p50Us: us(at(0.5)), + p95Us: us(at(0.95)), + maxUs: us(sorted[sorted.length - 1] ?? 0), + }; +}; + +const format = (label: string, stats: Stats) => + `${label}: ${stats.calls} calls, mean ${stats.meanUs} µs, p50 ${stats.p50Us} µs, p95 ${stats.p95Us} µs, max ${stats.maxUs} µs`; + +const IndicatorCost = () => { + const indicatorRef = + useRef>(null); + const listRef = useRef>(null); + const scrollDurations = useRef([]); + const readDurations = useRef([]); + const readSink = useRef(0); + const probeFlag = useSharedValue(false); + const probeLayout = useSharedValue({ x: 0, y: 0, height: 0, width: 0 }); + const [loopReport, setLoopReport] = useState('Loop: -'); + const [scrollReport, setScrollReport] = useState('Scroll: -'); + const [readsReport, setReadsReport] = useState('Reads: -'); + + const onScroll = useCallback( + (event: NativeSyntheticEvent) => { + const { contentOffset, contentSize, layoutMeasurement } = + event.nativeEvent; + const scrollable = contentSize.height - layoutMeasurement.height; + const offsetPercentage = + scrollable > 0 + ? Math.min(1, Math.max(0, contentOffset.y / scrollable)) + : 0; + const start = performance.now(); + indicatorRef.current?.onScrollToOffsetPercentage(offsetPercentage); + scrollDurations.current.push(performance.now() - start); + + const readStart = performance.now(); + readSink.current += (probeFlag.value ? 1 : 0) + probeLayout.value.height; + readDurations.current.push(performance.now() - readStart); + }, + [probeFlag, probeLayout] + ); + + const scrollToOffsetPercentage = useCallback((offsetPercentage: number) => { + const scrollable = ROWS.length * ROW_HEIGHT; + listRef.current?.scrollToOffset({ + offset: offsetPercentage * scrollable, + animated: false, + }); + }, []); + + const loop = useCallback((calls: number = LOOP_CALLS) => { + const durations: number[] = []; + for (let i = 0; i < calls; i++) { + const start = performance.now(); + indicatorRef.current?.onScrollToOffsetPercentage(i / calls); + durations.push(performance.now() - start); + } + const stats = toStats(durations); + setLoopReport(format('Loop', stats)); + return stats; + }, []); + + const scrollStats = useCallback(() => { + const handle = toStats(scrollDurations.current); + const reads = toStats(readDurations.current); + setScrollReport(format('Scroll', handle)); + setReadsReport(format('Reads', reads)); + return { handle, reads }; + }, []); + + const reset = useCallback(() => { + scrollDurations.current = []; + readDurations.current = []; + setScrollReport('Scroll: -'); + setReadsReport('Reads: -'); + }, []); + + useEffect(() => { + (global as { __indicatorCost?: unknown }).__indicatorCost = { + loop, + scrollStats, + reset, + }; + }, [loop, reset, scrollStats]); + + return ( + + + + loop()}> + Loop + + + Scroll stats + + + Reset + + + + {loopReport} + + + {scrollReport} + + + {readsReport} + + + + ( + + Row {item + 1} + + )} + /> + + + + + + ); +}; + +const styles = StyleSheet.create({ + container: { flex: 1 }, + panel: { padding: 12, backgroundColor: '#1F3A5F' }, + buttons: { flexDirection: 'row', marginBottom: 8 }, + button: { + color: 'white', + fontWeight: '600', + backgroundColor: '#2E5A8F', + paddingHorizontal: 12, + paddingVertical: 6, + borderRadius: 6, + marginRight: 8, + }, + report: { color: 'white', fontSize: 12, marginTop: 2 }, + listContainer: { flex: 1 }, + row: { + height: ROW_HEIGHT, + justifyContent: 'center', + paddingHorizontal: 16, + borderBottomWidth: StyleSheet.hairlineWidth, + borderBottomColor: '#ddd', + }, + indicator: { position: 'absolute', top: 0, bottom: 0, right: 1 }, +}); + +export default IndicatorCost; diff --git a/example/src/screens.ts b/example/src/screens.ts index 06cad8e..d5a45ac 100644 --- a/example/src/screens.ts +++ b/example/src/screens.ts @@ -7,4 +7,5 @@ export type RootStackParamList = { DotsLayout: undefined; MemoryLeak: undefined; ReplaceSections: undefined; + IndicatorCost: undefined; }; diff --git a/src/FastScrollIndicator/FastScrollIndicator.tsx b/src/FastScrollIndicator/FastScrollIndicator.tsx index eefc4eb..269359c 100644 --- a/src/FastScrollIndicator/FastScrollIndicator.tsx +++ b/src/FastScrollIndicator/FastScrollIndicator.tsx @@ -5,7 +5,7 @@ import React, { useEffect, useMemo, } from 'react'; -import { StyleSheet, ColorValue } from 'react-native'; +import { StyleSheet, ColorValue, LayoutChangeEvent } from 'react-native'; import { Gesture, GestureDetector } from 'react-native-gesture-handler'; import Animated, { runOnJS, @@ -110,10 +110,28 @@ export const FastScrollIndicator = React.forwardRef( const translateY = useSharedValue(0); const scale = useSharedValue(1); const translateFastScrollBarXTimer = useRef(null); - const disableOnScrollEvent = useSharedValue(false); - const viewLayout = useSharedValue({ x: 0, y: 0, height: 0, width: 0 }); + // Apps call onScrollToOffsetPercentage on every scroll frame. On + // Reanimated 3, reading a shared value from JS takes the UI runtime's + // lock, so the JS thread waits while the UI thread runs worklets, which + // it does on every frame of a scroll (this thumb's springs, at least). + // So that handle reads JS copies instead: the track's height, kept from + // onLayout, and whether a finger is on the track, set from the pan's + // onBegin and onFinalize. + const trackHeight = useRef(0); + const fingerOnTrack = useRef(false); + const setFingerOnTrack = useCallback((isOnTrack: boolean) => { + fingerOnTrack.current = isOnTrack; + }, []); + const onTrackLayout = useCallback( + (event: LayoutChangeEvent) => { + viewLayout.value = event.nativeEvent.layout; + trackHeight.current = event.nativeEvent.layout.height; + }, + [viewLayout] + ); + const clearTimeoutFastScrollBar = useCallback(() => { if (translateFastScrollBarXTimer.current != null) { clearTimeout(translateFastScrollBarXTimer.current); @@ -195,7 +213,6 @@ export const FastScrollIndicator = React.forwardRef( const { yPosition, yPercentage } = calculateYPosition(y); translateY.value = yPosition; processScroll(yPercentage); - disableOnScrollEvent.value = true; runOnJS(clearTimeoutFastScrollBar)(); }; @@ -206,6 +223,8 @@ export const FastScrollIndicator = React.forwardRef( // The finger touches the track .onBegin((event) => { scale.value = thumbScaleOnPress; + // Before the list scrolls: its scroll events are ignored from now on. + runOnJS(setFingerOnTrack)(true); followFinger(event.y); }) // The finger has moved far enough to activate the pan, then moves on @@ -217,16 +236,16 @@ export const FastScrollIndicator = React.forwardRef( processScroll(yPercentage); translateY.value = yPosition; scale.value = 1; - disableOnScrollEvent.value = false; + runOnJS(setFingerOnTrack)(false); runOnJS(scheduleHideFastScrollbar)(); }) ); }, [ clearTimeoutFastScrollBar, - disableOnScrollEvent, processScrollJSThread, scale, scheduleHideFastScrollbar, + setFingerOnTrack, thumbHeight, thumbScaleOnPress, translateY, @@ -260,13 +279,13 @@ export const FastScrollIndicator = React.forwardRef( return; } - if (disableOnScrollEvent.value) { + if (fingerOnTrack.current) { // event is ignored as the scrolling is being done by the thumbs return; } translateY.value = - offsetPercentage * (viewLayout.value.height - thumbSize.height); + offsetPercentage * (trackHeight.current - thumbSize.height); showFastScrollBar(); }, @@ -308,7 +327,7 @@ export const FastScrollIndicator = React.forwardRef( (viewLayout.value = event.nativeEvent.layout)} + onLayout={onTrackLayout} > {visible && (