哪个正则表达式更快?

时间:2015-12-13 20:27:28

标签: javascript regex

如果我想匹配Aa,以下哪个regexp会更快找到它?

/[Aa]/

/A/i

如何 许多 步骤

1 个答案:

答案 0 :(得分:1)

请尝试检查:

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,console

PS:
使用异步脚本可能会有点困难。