Skip to content

Copying an RE2 without recompiling / how best to replace inline regex literals #162

Closed Answered by uhop
matthewvalentine asked this question in Q&A
Discussion options

You must be logged in to vote

Finally, I got to measure, and copying an RE2 object is faster because it saves on internal translations:

const re = /A(B|C+)+D/,
  re2 = new RE2(re);

new RE2('A(B|C+)+D');
new RE2(re);
new RE2(re2);  // the fastest out of these three

If you can safely reuse then the code like that can be the fastest:

const lastIndex = re2.lastIndex;
re2.exec(string);
re2.lastIndex = lastIndex;

Raw data

The test:

import show from 'nano-bench/show.js';

import RE2 from 're2';

const re = /A(B|C+)+D/,
  re2 = new RE2(re),
  string = 'ACCCCCCCCCCCCCCCCX';

console.log('RegExp:');
await show({
  'regexp-inline': n => {
    for (let i = 0; i < n; ++i) /A(B|C+)+D/.test(string);
  },
  'regexp-copy': n => {
    f…

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by matthewvalentine
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants