ApliNi / blog

GNU General Public License v3.0
2 stars 0 forks source link

在 JS 中快速判断一个字符串包含其他多个字符串 #14

Open ApliNi opened 1 year ago

ApliNi commented 1 year ago

可以在浏览器控制台中运行这段代码:

// 测试字符串和循环次数
const str = `
            UPDATE serverTracker SET
                time = $time,
                online = $online,
                playerNum = $playerNum,
                maxPlayerNum = $maxPlayerNum,
                ping = $ping
            WHERE id = $id;
`;
const quantity = 100000;
let index = 0;

console.time('includes');
for (let i = 0; i < quantity; i++) {
    if(str.includes('DELETE') || str.includes('UPDATE') || str.includes('INSERT')){
        index ++;
    }
}
console.timeEnd('includes');

console.time('indexOf');
for (let i = 0; i < quantity; i++) {
    if(str.indexOf('DELETE') !== -1 || str.indexOf('UPDATE') !== -1 || str.indexOf('INSERT') !== -1){
        index ++;
    }
}
console.timeEnd('indexOf');

const reg = new RegExp(/DELETE|UPDATE|INSERT/);
console.time('RegExpTest');
for (let i = 0; i < quantity; i++) {
    if(reg.test(str)){
        index ++;
    }
}
console.timeEnd('RegExpTest');

// 正则表达式测试, 但是每次重新定义正则
console.time('RegExpTest2');
for (let i = 0; i < quantity; i++) {
    if(new RegExp(/DELETE|UPDATE|INSERT/).test(str)){
        index ++;
    }
}
console.timeEnd('RegExpTest2');

结果

对于固定的多个字符串包含检查, 正则表达式 test 比其他方法更快. 如果要判断的字符串每一次都不固定, 则正则表达式因需要重新初始化而最慢.

// 控制台输出
includes: 6.36181640625 ms
VM131:30 indexOf: 7.60400390625 ms
VM131:40 RegExpTest: 3.18603515625 ms
VM131:50 RegExpTest2: 16.01513671875 ms