Optimize flattenStyle for nested style arrays (#57203)

Summary:
- Walk nested style arrays directly into one result object instead of recursively allocating intermediate flattened objects.
- Preserve existing behavior for object styles, falsy entries, and later-style override order.
- Add focused unit coverage for array inputs that must still allocate merged result objects.

## Benchmark proof
External reproducible benchmark app:
https://github.com/tarikfp/rn-style-flatten-benchmark

Latest `yarn bench:compare` from the benchmark repo compares React Native `main` at `066c0d8bd8` against this branch at `81b5bc26b6`:

| scenario | before median ms | after median ms | change |
| --- | ---: | ---: | ---: |
| nested single style array | 294.79 | 98.73 | 66.5% faster |
| nested merged style array | 278.54 | 122.06 | 56.2% faster |

This is not a blanket claim that every React Native screen becomes 50%+ faster. It is targeted to the `flattenStyle` path when composed components pass nested style arrays.

## Validation
- `yarn test` in benchmark app repo
- `yarn lint` in benchmark app repo
- `yarn workspace style-flatten-benchmark-app tsc --noEmit`
- `yarn bench:compare`
- `yarn test packages/react-native/Libraries/StyleSheet/__tests__/flattenStyle-test.js --runInBand` in the React Native checkout
- iOS simulator build/install for the benchmark app

Draft while broader upstream validation is gathered.

## Affected areas

`flattenStyle` is not only the public `StyleSheet.flatten` helper. Core React Native components call it when they need to read or normalize style props before passing work further down:

- `Text` uses it in `packages/react-native/Libraries/Text/Text.js:188` before normalizing text style values such as numeric `fontWeight` and text selection-related props.
- `Image` uses it on both platforms: `Image.ios.js:141` reads `objectFit`, `resizeMode`, and `tintColor`; `Image.android.js:310` reads `objectFit` and `resizeMode` before building native props.
- `ImageBackground` uses it in `packages/react-native/Libraries/Image/ImageBackground.js:72` before splitting size-related style values between the wrapper view and inner image.
- `TextInput` uses it in `packages/react-native/Libraries/Components/TextInput/TextInput.js:655` while preserving the original style when possible, but still flattening to normalize text style overrides.
- `TouchableOpacity` uses it in `packages/react-native/Libraries/Components/Touchable/TouchableOpacity.js:260` and `:364` to read opacity from `style` when setting and updating its animated opacity.
- `ScrollView` uses it in `packages/react-native/Libraries/Components/ScrollView/ScrollView.js:1663` for development-time layout warnings and in `:1850` when splitting outer and inner layout props around refresh controls.
- `Animated.ScrollView` uses the same split path in `packages/react-native/Libraries/Animated/components/AnimatedScrollView.js:94`.
- Animated props use it in `packages/react-native/Libraries/Animated/nodes/AnimatedProps.js:62` and `:157`, and the newer memo hook uses it in `packages/react-native/src/private/animated/createAnimatedPropsMemoHook.js:125`, so nested style arrays also matter for animated style props.
- Fabric public instances use it in `packages/react-native/Libraries/ReactNative/ReactFabricPublicInstance/ReactNativeAttributePayload.js:186` and `:195` before diffing array style props.
- Developer tooling also goes through it: the element inspector uses it in `ElementProperties.js:43` and `ElementBox.js:34`, and React DevTools receives it as the React Native style resolver from `setUpReactDevTools.js:74`.

That is why the benchmark focuses on nested style arrays instead of claiming every render gets faster. The change helps when those call sites receive styles composed like `style={[base, condition && extra, [override]]}`.

## Changelog:

[GENERAL] [CHANGED] - Make `flattenStyle` avoid extra intermediate objects when flattening nested style arrays.

Pull Request resolved: https://github.com/react/react-native/pull/57203

Test Plan:
- Ran the focused React Native unit test: `yarn test packages/react-native/Libraries/StyleSheet/__tests__/flattenStyle-test.js --runInBand`.
- Ran the external benchmark app checks: `yarn test`, `yarn lint`, and `yarn workspace style-flatten-benchmark-app tsc --noEmit`.
- Ran `yarn bench:compare` in the benchmark app repo. The latest saved result compares React Native `main` at `066c0d8bd8` with this branch at `81b5bc26b6` and shows the nested style-array cases improving from `294.79 ms` to `98.73 ms` and from `278.54 ms` to `122.06 ms`.
- Built and installed the benchmark app on iOS simulators to compare a `main` build and this branch side by side.

Reviewed By: javache

Differential Revision: D108616011

Pulled By: Abbondanzo

fbshipit-source-id: f1540a274b6919c43d137d6587ea4d11be258796
This commit is contained in:
Tarık authored and meta-codesync[bot] committed 2026-06-15 15:48:20 -07:00
1 parent 9d54391814
commit d26f7b338d
3 files changed
+131 -13

No files matched your search

@@ -0,0 +1,72 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
*/
import '@react-native/fantom/src/setUpDefaultReactNativeEnvironment';
import flattenStyle from '../flattenStyle';
import * as Fantom from '@react-native/fantom';
const baseStyle = {
width: 100,
height: 40,
opacity: 0.8,
backgroundColor: 'blue',
borderRadius: 8,
};
const overrideStyle = {
height: 44,
opacity: 1,
borderWidth: 1,
borderColor: 'red',
};
const accentStyle = {
borderRadius: 12,
transform: [{scale: 1.1}],
};
const objectStyle = baseStyle;
const singleArrayStyle = [baseStyle];
const singleEffectiveArrayStyle: $FlowFixMe = [
null,
false,
undefined,
baseStyle,
];
const nestedSingleArrayStyle: $FlowFixMe = [
null,
[undefined, baseStyle],
false,
];
const nestedMergedArrayStyle = [baseStyle, [null, overrideStyle, accentStyle]];
const mergedArrayStyle = [baseStyle, overrideStyle];
Fantom.unstable_benchmark
.suite('flattenStyle', {minTestExecutionTimeMs: 500})
.test('flatten object style', () => {
flattenStyle(objectStyle);
})
.test('flatten array with one style', () => {
flattenStyle(singleArrayStyle);
})
.test('flatten array with one effective style', () => {
flattenStyle(singleEffectiveArrayStyle);
})
.test('flatten nested array with one effective style', () => {
flattenStyle(nestedSingleArrayStyle);
})
.test('flatten nested array with merged styles', () => {
// $FlowFixMe[incompatible-call]
flattenStyle(nestedMergedArrayStyle);
})
.test('flatten array with merged styles', () => {
flattenStyle(mergedArrayStyle);
});
@@ -94,6 +94,37 @@ describe('flattenStyle', () => {
});
});
it('should allocate an object when an array contains one style', () => {
const style = {a: 'b'};
const singleStyle = flattenStyle([style]);
expect(singleStyle).not.toBe(style);
expect(singleStyle).toEqual(style);
});
it('should allocate an object when an array contains one effective style', () => {
const style = {a: 'b'};
const singleStyle = flattenStyle([null, false, undefined, style]);
const singleStyleAgain = flattenStyle([null, [undefined, style], false]);
expect(singleStyle).not.toBe(style);
expect(singleStyleAgain).not.toBe(style);
expect(singleStyle).toEqual(style);
expect(singleStyleAgain).toEqual(style);
});
it('should allocate an object when merging multiple styles', () => {
const style1 = {width: 10};
const style2 = {height: 20};
const flatStyle = flattenStyle([style1, style2]);
expect(flatStyle).not.toBe(style1);
expect(flatStyle).not.toBe(style2);
expect(style1).toEqual({width: 10});
expect(style2).toEqual({height: 20});
expect(flatStyle).toEqual({width: 10, height: 20});
});
it('should merge single class and style properly', () => {
const fixture = getFixture();
const style = {styleA: 'overrideA', styleC: 'overrideC'};
+28 -13
View File
@@ -20,6 +20,31 @@ type NonAnimatedNodeObject<TStyleProp> = TStyleProp extends AnimatedNode
? empty
: TStyleProp;
function flattenStyleArrayInto<
TStyleProp extends ____DangerouslyImpreciseAnimatedStyleProp_Internal,
>(result: {[string]: $FlowFixMe}, styles: ReadonlyArray<?TStyleProp>) {
for (let i = 0, styleLength = styles.length; i < styleLength; ++i) {
const style = styles[i];
if (style === null || typeof style !== 'object') {
continue;
}
if (Array.isArray(style)) {
// $FlowFixMe[underconstrained-implicit-instantiation]
flattenStyleArrayInto(result, style);
continue;
}
// $FlowFixMe[invalid-in-rhs]
for (const key in style) {
// $FlowFixMe[incompatible-use]
// $FlowFixMe[invalid-computed-prop]
// $FlowFixMe[prop-missing]
result[key] = style[key];
}
}
}
function flattenStyle<
TStyleProp extends ____DangerouslyImpreciseAnimatedStyleProp_Internal,
>(
@@ -36,19 +61,9 @@ function flattenStyle<
}
const result: {[string]: $FlowFixMe} = {};
for (let i = 0, styleLength = style.length; i < styleLength; ++i) {
// $FlowFixMe[underconstrained-implicit-instantiation]
const computedStyle = flattenStyle(style[i]);
if (computedStyle) {
// $FlowFixMe[invalid-in-rhs]
for (const key in computedStyle) {
// $FlowFixMe[incompatible-use]
// $FlowFixMe[invalid-computed-prop]
// $FlowFixMe[prop-missing]
result[key] = computedStyle[key];
}
}
}
// $FlowFixMe[underconstrained-implicit-instantiation]
flattenStyleArrayInto(result, style);
// $FlowFixMe[incompatible-type]
return result;
}