gpt4 book ai didi

javascript - JavaScript 多久编译一次函数中的正则表达式?

转载 作者:行者123 更新时间:2023-12-02 04:39:29 28 4
gpt4 key购买 nike

鉴于此功能:

function doThing(values,things){
var thatRegex = /^http:\/\//i; // is this created once or on every execution?
if (values.match(thatRegex)) return values;
return things;
}

JavaScript 引擎多久需要创建一次正则表达式?每次执行一次还是每次页面加载/脚本解析一次?

为了防止不必要的答案或评论,我个人倾向于将正则表达式放在函数外部,而不是内部。问题是关于语言的行为,因为我不确定在哪里查找它,或者这是否是引擎问题。

<小时/>

编辑:

有人提醒我我没有提到这将在循环中使用。我的歉意:

var newList = [];
foreach(item1 in ListOfItems1){
foreach(item2 in ListOfItems2){
newList.push(doThing(item1, item2));
}
}

因此,鉴于它将在循环中多次使用,因此在函数外部定义正则表达式是有意义的,但这就是想法。

还请注意,该脚本相当通用,仅用于检查正则表达式创建的行为和成本

最佳答案

来自Mozilla's JavaScript Guide关于正则表达式:

Regular expression literals provide compilation of the regular expression when the script is evaluated. When the regular expression will remain constant, use this for better performance.

来自ECMA-262 spec ,§7.8.5 正则表达式文字:

A regular expression literal is an input element that is converted to a RegExp object (see 15.10) each time the literal is evaluated.

换句话说,当它被评估为第一次解析脚本时,它会被编译一次。

还值得注意的是,根据 ES5 规范,两个文字将编译为 RegExp两个不同实例,即使文字他们自己都是一样的。因此,如果给定的文字在脚本中出现两次,它将被编译两次,形成两个不同的实例:

Two regular expression literals in a program evaluate to regular expression objects that never compare as === to each other even if the two literals' contents are identical.

...

... each time the literal is evaluated, a new object is created as if by the expression new RegExp(Pattern, Flags) where RegExp is the standard built-in constructor with that name.

关于javascript - JavaScript 多久编译一次函数中的正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8814009/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com