Backtracking regex

Benchmark created on


Description

Demonstrate how .* at the beginning of a regular expression is Very Expensive™

Setup

const longMiss = '0123456789abcdef'.repeat(2 ** 10); // 16 * 2^10 = 16K characters
const longHit = longMiss + ' should be number';
function assert(pred) {
	if (!pred) throw new Error('Unexpected result!');
}

Test runner

Ready to run.

Testing in
TestOps/sec
No caret, miss
const match = /.* should be number/.exec(longMiss);
assert(match === null);
ready
No caret, hit
const match = /.* should be number/.exec(longHit);
assert(match[0] === longHit); // match the full string
ready
Yes caret, miss
const match = /^.* should be number/.exec(longMiss);
assert(match === null);
ready
Yes caret, hit
const match = /^.* should be number/.exec(longHit);
assert(match[0] === longHit); // match the full string
ready
Yes caret, non-greedy, miss
const match = /^.*? should be number/.exec(longMiss);
assert(match === null);
ready
Yes caret, non-greedy, hit
const match = /^.*? should be number/.exec(longHit);
assert(match[0] === longHit); // match the full string
ready

Revisions

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