Skip to content

useTopLevelRegex

诊断类别:lint/performance/useTopLevelRegex

¥Diagnostic Category: lint/performance/useTopLevelRegex

自从:v1.8.0 要求在顶层声明正则表达式文字。

¥Since: v1.8.0 Require regex literals to be declared at the top level.

此规则对于避免在多次调用的函数(热路径)中使用正则表达式文字时的性能问题很有用。正则表达式文字在评估时会创建一个新的 RegExp 对象。(参见 https://web.nodejs.cn/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp)通过在顶层声明它们,可以避免这种开销。

¥This rule is useful to avoid performance issues when using regex literals inside functions called many times (hot paths). Regex literals create a new RegExp object when they are evaluated. (See https://web.nodejs.cn/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) By declaring them at the top level, this overhead can be avoided.

需要注意的是,并不建议在所有情况下都使用此规则。将正则表达式文字放在顶层可能会影响启动时间。在浏览器环境中,这可能会导致更长的页面加载时间。

¥It’s important to note that this rule is not recommended for all cases. Placing regex literals at the top level can hurt startup times. In browser contexts, this can result in longer page loads.

此外,此规则忽略带有 g 和/或 y 标志的正则表达式,因为它们保持内部状态,并且在使用它们调用 testexec 时可能导致 副作用

¥Additionally, this rule ignores regular expressions with the g and/or y flags, as they maintain internal state and can cause side effects when calling test and exec with them.

¥Examples

¥Invalid

function foo(someString) {
return /[a-Z]*/.test(someString)
}
code-block.js:2:12 lint/performance/useTopLevelRegex ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

This regex literal is not defined in the top level scope. This can lead to performance issues if this function is called frequently.

1 │ function foo(someString) {
> 2 │ return /[a-Z]*/.test(someString)
^^^^^^^^
3 │ }
4 │

Move the regex literal outside of this scope, and place it at the top level of this module, as a constant.

¥Valid

const REGEX = /[a-Z]*/;
function foo(someString) {
return REGEX.test(someString)
}
function foo(str) {
return /[a-Z]*/g.exec(str)
}

¥Related links