Hoist regex patterns to module-level in StyleSheet processors (#56022)

Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/56022

Changelog: [Internal]

Hoist inline regex patterns to module-level constants in processFilter.js, processBackgroundImage.js, and processTransformOrigin.js to avoid repeated regex compilation on each function call.

Fantom benchmark results (p50 latency, optimized build).

| Benchmark | Before | After | Improvement |
|---|---|---|---|
| 100 views with filter strings | 4.427ms | 3.556ms | 24.48% faster |
| 500 views with filter strings | 22.523ms | 17.861ms | 26.10% faster |
| 100 views with boxShadow strings | 5.835ms | 5.729ms | 1.85% faster |
| 500 views with boxShadow strings | 29.914ms | 28.846ms | 3.70% faster |
| 100 views with transformOrigin strings | 2.521ms | 2.512ms | 0.36% faster |
| 500 views with transformOrigin strings | 12.706ms | 12.421ms | 2.30% faster |

Reviewed By: javache

Differential Revision: D95853070

fbshipit-source-id: 788a656fcc626fe0da73fa689298114e53f3b031
This commit is contained in:
Samuel Susla authored and meta-codesync[bot] committed 2026-03-10 11:25:21 -07:00
1 parent 6e38fd7e3f
commit c35f3e6696
3 files changed
+45 -20

No files matched your search

@@ -20,6 +20,14 @@ import type {
const processColor = require('./processColor').default;
// Pre-compiled regex patterns for performance - avoids regex compilation on each call
const NEWLINE_REGEX = /\n/g;
const GRADIENT_REGEX = /^(linear|radial)-gradient\(((?:\([^)]*\)|[^()])*)\)/;
const COMMA_SPLIT_REGEX = /,(?![^(]*\))/;
const WHITESPACE_SPLIT_REGEX = /\s+/;
const COLOR_STOP_PARTS_REGEX = /\S+\([^)]*\)|\S+/g;
const WHITESPACE_NORMALIZE_REGEX = /\s+/g;
// Linear Gradient
const LINEAR_GRADIENT_DIRECTION_REGEX =
/^to\s+(?:top|bottom|left|right)(?:\s+(?:top|bottom|left|right))?/i;
@@ -81,7 +89,9 @@ export default function processBackgroundImage(
}
if (typeof backgroundImage === 'string') {
result = parseBackgroundImageCSSString(backgroundImage.replace(/\n/g, ' '));
result = parseBackgroundImageCSSString(
backgroundImage.replace(NEWLINE_REGEX, ' '),
);
} else if (Array.isArray(backgroundImage)) {
for (const bgImage of backgroundImage) {
const processedColorStops = processColorStops(bgImage);
@@ -255,9 +265,7 @@ function parseBackgroundImageCSSString(
for (const bgImageString of bgImageStrings) {
const bgImage = bgImageString.toLowerCase();
const gradientRegex = /^(linear|radial)-gradient\(((?:\([^)]*\)|[^()])*)\)/;
const match = gradientRegex.exec(bgImage);
const match = GRADIENT_REGEX.exec(bgImage);
if (match) {
const [, type, gradientContent] = match;
const isRadial = type.toLowerCase() === 'radial';
@@ -281,7 +289,7 @@ function parseRadialGradientCSSString(
let position: RadialGradientPosition = {...DEFAULT_RADIAL_POSITION};
// split the content by commas, but not if inside parentheses (for color values)
const parts = gradientContent.split(/,(?![^(]*\))/);
const parts = gradientContent.split(COMMA_SPLIT_REGEX);
// first part may contain shape, size, and position
// [ <radial-shape> || <radial-size> ]? [ at <position> ]?
const firstPartStr = parts[0].trim();
@@ -289,7 +297,7 @@ function parseRadialGradientCSSString(
let hasShapeSizeOrPositionString = false;
let hasExplicitSingleSize = false;
let hasExplicitShape = false;
const firstPartTokens = firstPartStr.split(/\s+/);
const firstPartTokens = firstPartStr.split(WHITESPACE_SPLIT_REGEX);
// firstPartTokens is the shape, size, and position
while (firstPartTokens.length > 0) {
@@ -626,13 +634,13 @@ function parseColorStopsCSSString(parts: Array<string>): Array<{
position: ColorStopPosition,
}> = [];
// split by comma, but not if it's inside a parentheses. e.g. red, rgba(0, 0, 0, 0.5), green => ["red", "rgba(0, 0, 0, 0.5)", "green"]
const stops = colorStopsString.split(/,(?![^(]*\))/);
const stops = colorStopsString.split(COMMA_SPLIT_REGEX);
let prevStop = null;
for (let i = 0; i < stops.length; i++) {
const stop = stops[i];
const trimmedStop = stop.trim().toLowerCase();
// Match function like pattern or single words
const colorStopParts = trimmedStop.match(/\S+\([^)]*\)|\S+/g);
const colorStopParts = trimmedStop.match(COLOR_STOP_PARTS_REGEX);
if (colorStopParts == null) {
// If a color stop is invalid, return null and do not apply any gradient. Same as web.
return null;
@@ -726,7 +734,9 @@ function getDirectionForKeyword(direction?: string): ?LinearGradientDirection {
return null;
}
// Remove extra whitespace
const normalized = direction.replace(/\s+/g, ' ').toLowerCase();
const normalized = direction
.replace(WHITESPACE_NORMALIZE_REGEX, ' ')
.toLowerCase();
switch (normalized) {
case 'to top':
+16 -8
View File
@@ -15,6 +15,14 @@ import type {DropShadowValue, FilterFunction} from './StyleSheetTypes';
import processColor from './processColor';
// Pre-compiled regex patterns for performance - avoids regex compilation on each call
const NEWLINE_REGEX = /\n/g;
const FILTER_FUNCTION_REGEX =
/([\w-]+)\(([^()]*|\([^()]*\)|[^()]*\([^()]*\)[^()]*)\)/g;
const ARGS_WITH_UNITS_REGEX = /([+-]?\d*(\.\d+)?)([a-zA-Z%]+)?/g;
const WHITESPACE_SPLIT_REGEX = /\s+(?![^(]*\))/;
const LENGTH_PARSE_REGEX = /([+-]?\d*(\.\d+)?)([\w\W]+)?/g;
type ParsedFilter =
| {brightness: number}
| {blur: number}
@@ -43,13 +51,13 @@ export default function processFilter(
}
if (typeof filter === 'string') {
filter = filter.replace(/\n/g, ' ');
filter = filter.replace(NEWLINE_REGEX, ' ');
// matches on functions with args and nested functions like "drop-shadow(10 10 10 rgba(0, 0, 0, 1))"
const regex = /([\w-]+)\(([^()]*|\([^()]*\)|[^()]*\([^()]*\)[^()]*)\)/g;
FILTER_FUNCTION_REGEX.lastIndex = 0;
let matches;
while ((matches = regex.exec(filter))) {
while ((matches = FILTER_FUNCTION_REGEX.exec(filter))) {
let filterName = matches[1].toLowerCase();
if (filterName === 'drop-shadow') {
const dropShadow = parseDropShadow(matches[2]);
@@ -120,8 +128,8 @@ function _getFilterAmount(filterName: string, filterArgs: unknown): ?number {
let unit: string;
if (typeof filterArgs === 'string') {
// matches on args with units like "1.5 5% -80deg"
const argsWithUnitsRegex = new RegExp(/([+-]?\d*(\.\d+)?)([a-zA-Z%]+)?/g);
const match = argsWithUnitsRegex.exec(filterArgs);
ARGS_WITH_UNITS_REGEX.lastIndex = 0;
const match = ARGS_WITH_UNITS_REGEX.exec(filterArgs);
if (!match || isNaN(Number(match[1]))) {
return undefined;
@@ -258,7 +266,7 @@ function parseDropShadowString(rawDropShadow: string): ?DropShadowValue {
let keywordDetectedAfterLength = false;
// split args by all whitespaces that are not in parenthesis
for (const arg of rawDropShadow.split(/\s+(?![^(]*\))/)) {
for (const arg of rawDropShadow.split(WHITESPACE_SPLIT_REGEX)) {
const processedColor = processColor(arg);
if (processedColor != null) {
if (dropShadow.color != null) {
@@ -305,8 +313,8 @@ function parseDropShadowString(rawDropShadow: string): ?DropShadowValue {
function parseLength(length: string): ?number {
// matches on args with units like "1.5 5% -80deg"
const argsWithUnitsRegex = /([+-]?\d*(\.\d+)?)([\w\W]+)?/g;
const match = argsWithUnitsRegex.exec(length);
LENGTH_PARSE_REGEX.lastIndex = 0;
const match = LENGTH_PARSE_REGEX.exec(length);
if (!match || Number.isNaN(match[1])) {
return null;
@@ -10,6 +10,9 @@
import invariant from 'invariant';
// Pre-compiled regex pattern for performance - avoids regex compilation on each call
const TRANSFORM_ORIGIN_REGEX = /(top|bottom|left|right|center|\d+(?:%|px)|0)/gi;
const INDEX_X = 0;
const INDEX_Y = 1;
const INDEX_Z = 2;
@@ -20,12 +23,14 @@ export default function processTransformOrigin(
): Array<string | number> {
if (typeof transformOrigin === 'string') {
const transformOriginString = transformOrigin;
const regex = /(top|bottom|left|right|center|\d+(?:%|px)|0)/gi;
TRANSFORM_ORIGIN_REGEX.lastIndex = 0;
const transformOriginArray: Array<string | number> = ['50%', '50%', 0];
let index = INDEX_X;
let matches;
outer: while ((matches = regex.exec(transformOriginString))) {
outer: while (
(matches = TRANSFORM_ORIGIN_REGEX.exec(transformOriginString))
) {
let nextIndex = index + 1;
const value = matches[0];
@@ -53,7 +58,9 @@ export default function processTransformOrigin(
// Handle [[ center | left | right ] && [ center | top | bottom ]] <length>?
if (index === INDEX_X) {
const horizontal = regex.exec(transformOriginString);
const horizontal = TRANSFORM_ORIGIN_REGEX.exec(
transformOriginString,
);
if (horizontal == null) {
break outer;
}