哪个regexp更快

Which regexp is faster?

本文关键字:更快 regexp 哪个      更新时间:2023-09-26

如果我想匹配Aa,下面的regexp中哪一个会更快?

/[Aa]/

/A/i

有多少步骤

试着这样检查:

function time_my_script(script) {
    var start = window.performance.now();
    script();
    return window.performance.now() - start;
}
time_a = time_my_script(function() {
    var text = 'This is a test string, make it a long one to actually test well';
    var patt = new RegExp(/[Aa]/);
    var res = patt.test(text);
});
time_b = time_my_script(function() {
    var text = 'This is a test string, make it a long one to actually test well';
    var patt = new RegExp(/A/i);
    var res = patt.test(text);
});
console.log('Time A ' + time_a);
console.log('Time B ' + time_b);

JSFiddle:https://jsbin.com/gasayarivu/edit?js,控制台

附言:
对于异步脚本,这可能会有点困难。