Regex performance

Benchmark created on


Setup

const compileRegex = (pattern, flags) => {
    try {
        return new RegExp(pattern, flags);
    } catch (e) {}
};

const compileRegexesCondensed = (res) =>
    res
        .reduce((acc, re) => {
            const entryForFlags = acc.find((e) => e.f === re.f);

            if (!entryForFlags) {
                acc.push(re);
                return acc;
            }

            entryForFlags.p = entryForFlags.p + '|' + re.p;
            return acc;
        }, [])
        .flatMap((re) => compileRegex(re.p, re.f) || []);
        
 const compileRegexes = (res) =>
    res.reduce((acc, re) => {
        const regex = compileRegex(re.p, re.f);

        if (regex) {
            acc.push(regex);
        }

        return acc;
    }, []);
 
 const matchesREs = (str, patterns) => {
    // Validate our whitelisted patterns include the given URL:
    for (let i = 0; i < patterns.length; i++) {
        if (patterns[i].test(str)) {
            return true;
        }
    }

    return false;
};

 const patterns = [{p: 'abc', f: 'i'}, {p:'def', f:'i'}, {p:'ghi', f:'g'},{p:'jkl', f:'ig'},{p:'mno',f:'ig'},{p:'pqr', f:'ig'}, {p:'stu', f:''},{p:'vwx',f:''}, {p:'yz(', f:''}]
 const res = compileRegexes(patterns);
 const resc = compileRegexesCondensed(patterns);

Test runner

Ready to run.

Testing in
TestOps/sec
No consolidation by flags
matchesREs("stu", res)
ready
Consolidation by flags
matchesREs("stu", resc)
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.