Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 17 additions & 18 deletions docs/backlog.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
1 change: 1 addition & 0 deletions example/src/ExamplesScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export const ExamplesScreen = () => {
{ title: 'DotsLayout', destination: 'DotsLayout' },
{ title: 'MemoryLeak', destination: 'MemoryLeak' },
{ title: 'ReplaceSections', destination: 'ReplaceSections' },
{ title: 'IndicatorCost', destination: 'IndicatorCost' },
];
return (
<>
Expand Down
2 changes: 2 additions & 0 deletions example/src/NavigationTree.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<RootStackParamList>();

Expand All @@ -25,6 +26,7 @@ const NavigationTree = () => {
<Stack.Screen name="DotsLayout" component={DotsLayout} />
<Stack.Screen name="MemoryLeak" component={MemoryLeak} />
<Stack.Screen name="ReplaceSections" component={ReplaceSections} />
<Stack.Screen name="IndicatorCost" component={IndicatorCost} />
</Stack.Group>

<Stack.Group screenOptions={{ presentation: 'modal' }}>
Expand Down
217 changes: 217 additions & 0 deletions example/src/indicatorCost/IndicatorCost.tsx
Original file line number Diff line number Diff line change
@@ -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<React.ElementRef<typeof FastScrollIndicator>>(null);
const listRef = useRef<FlashList<number>>(null);
const scrollDurations = useRef<number[]>([]);
const readDurations = useRef<number[]>([]);
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<NativeScrollEvent>) => {
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 (
<View style={styles.container}>
<View style={styles.panel}>
<View style={styles.buttons}>
<Pressable testID="indicator-cost-loop" onPress={() => loop()}>
<Text style={styles.button}>Loop</Text>
</Pressable>
<Pressable testID="indicator-cost-scroll" onPress={scrollStats}>
<Text style={styles.button}>Scroll stats</Text>
</Pressable>
<Pressable testID="indicator-cost-reset" onPress={reset}>
<Text style={styles.button}>Reset</Text>
</Pressable>
</View>
<Text testID="indicator-cost-loop-report" style={styles.report}>
{loopReport}
</Text>
<Text testID="indicator-cost-scroll-report" style={styles.report}>
{scrollReport}
</Text>
<Text testID="indicator-cost-reads-report" style={styles.report}>
{readsReport}
</Text>
</View>
<View style={styles.listContainer}>
<FlashList
ref={listRef}
data={ROWS}
estimatedItemSize={ROW_HEIGHT}
onScroll={onScroll}
scrollEventThrottle={16}
renderItem={({ item }) => (
<View style={styles.row}>
<Text>Row {item + 1}</Text>
</View>
)}
/>
<View style={styles.indicator}>
<FastScrollIndicator
ref={indicatorRef}
scrollToOffsetPercentage={scrollToOffsetPercentage}
/>
</View>
</View>
</View>
);
};

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;
1 change: 1 addition & 0 deletions example/src/screens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@ export type RootStackParamList = {
DotsLayout: undefined;
MemoryLeak: undefined;
ReplaceSections: undefined;
IndicatorCost: undefined;
};
37 changes: 28 additions & 9 deletions src/FastScrollIndicator/FastScrollIndicator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -110,10 +110,28 @@ export const FastScrollIndicator = React.forwardRef(
const translateY = useSharedValue(0);
const scale = useSharedValue(1);
const translateFastScrollBarXTimer = useRef<NodeJS.Timeout | null>(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);
Expand Down Expand Up @@ -195,7 +213,6 @@ export const FastScrollIndicator = React.forwardRef(
const { yPosition, yPercentage } = calculateYPosition(y);
translateY.value = yPosition;
processScroll(yPercentage);
disableOnScrollEvent.value = true;
runOnJS(clearTimeoutFastScrollBar)();
};

Expand All @@ -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
Expand All @@ -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,
Expand Down Expand Up @@ -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();
},
Expand Down Expand Up @@ -308,7 +327,7 @@ export const FastScrollIndicator = React.forwardRef(
<Animated.View
style={styles.container}
testID={INDICATOR_TRACK_TEST_ID}
onLayout={(event) => (viewLayout.value = event.nativeEvent.layout)}
onLayout={onTrackLayout}
>
{visible && (
<Animated.View
Expand Down
Loading