项目文件夹

文件
2026-07-13 21:36:17 +08:00

1.1 KiB


title: 提升正则表达式创建性能 impact: LOW-MEDIUM impactDescription: 避免重复创建 tags: javascript, regexp, optimization, memoization

提升正则表达式创建性能

不要在渲染函数内创建 RegExp 对象。应将其提升到模块作用域,或使用 useMemo() 进行记忆化。

错误做法(每次渲染都新建 RegExp):

function Highlighter({ text, query }: Props) {
  const regex = new RegExp(`(${query})`, 'gi')
  const parts = text.split(regex)
  return <>{parts.map((part, i) => ...)}</>
}

正确做法(记忆化或提升):

const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/

function Highlighter({ text, query }: Props) {
  const regex = useMemo(
    () => new RegExp(`(${escapeRegex(query)})`, 'gi'),
    [query]
  )
  const parts = text.split(regex)
  return <>{parts.map((part, i) => ...)}</>
}

警告(全局正则表达式存在可变状态):

全局正则(/g)具有可变的 lastIndex 状态:

const regex = /foo/g
regex.test('foo')  // true, lastIndex = 3
regex.test('foo')  // false, lastIndex = 0