Skip to content

Commit

Permalink
RN: Optimize StyleSheet.compose
Browse files Browse the repository at this point in the history
Summary:
Changes two important aspects of `StyleSheet.compose`:

- Extract it from `StyleSheet` so that it can be imported from other internal modules without incurring circular dependencies. (Surprisingly, `StyleSheet` has a lot of dependencies.)
- Avoid a redundant `style1 != null` check.

Changelog:
[General][Changed] - Optimized performance of `StyleSheet.compose`

Reviewed By: sammy-SC

Differential Revision: D56621407
  • Loading branch information
yungsters authored and facebook-github-bot committed Apr 26, 2024
1 parent be06fd4 commit cbfcf25
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 10 deletions.
13 changes: 3 additions & 10 deletions packages/react-native/Libraries/StyleSheet/StyleSheet.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import type {
____ViewStyleProp_Internal,
} from './StyleSheetTypes';

import composeStyles from './composeStyles';

const ReactNativeStyleAttributes = require('../Components/View/ReactNativeStyleAttributes');
const PixelRatio = require('../Utilities/PixelRatio').default;
const flatten = require('./flattenStyle');
Expand Down Expand Up @@ -268,16 +270,7 @@ module.exports = {
* array, saving allocations and maintaining reference equality for
* PureComponent checks.
*/
compose<T: DangerouslyImpreciseStyleProp>(
style1: ?T,
style2: ?T,
): ?T | $ReadOnlyArray<T> {
if (style1 != null && style2 != null) {
return ([style1, style2]: $ReadOnlyArray<T>);
} else {
return style1 != null ? style1 : style2;
}
},
compose: composeStyles,

/**
* Flattens an array of style objects, into one aggregated style object.
Expand Down
27 changes: 27 additions & 0 deletions packages/react-native/Libraries/StyleSheet/composeStyles.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/**
* 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
* @format
*/

/**
* Combines two styles such that `style2` will override any styles in `style1`.
* If either style is null or undefined, the other one is returned without
* allocating an array, saving allocations and enabling memoization.
*/
export default function composeStyles<T1, T2>(
style1: ?T1,
style2: ?T2,
): ?(T1 | T2 | $ReadOnlyArray<T1 | T2>) {
if (style2 == null) {
return style1;
}
if (style1 == null) {
return style2;
}
return [style1, style2];
}

0 comments on commit cbfcf25

Please sign in to comment.