I have code like the following:
#include <regex>
int main()
{
char buf[35000] = {};
auto begin = std::cbegin(buf), end = std::cend(buf);
std::cmatch groups;
std::regex::flag_type flags = std::regex_constants::ECMAScript;
std::regex re(R"REGEX(^[x02-x7f]..[x01-x0c]..)REGEX", flags);
std::regex_search(begin, end, groups, re);
}
… and noticed that it performed suspiciously slowly.
Investigating, I plugged in different values for that buffer size, and found that the search gets slower as the buffer expands:
(small=100, large=35000, huge=100000; "unanchored" is with ^
omitted from the pattern)
The results are as I'd expect if I provide an input that actually matches the pattern:
std::regex
is not in multiline mode by default (right?), so I'd have thought that anchor (^
) would have prevented such shenanigans. Pattern not found at the start of the search string? Return no match, job done.
Seems to happen with both libc++ and libstdc++.
What am I missing about this? What's causing it?
Obvious workarounds include giving std::regex_search
just a prefix of the buffer (a prefix large enough to encompass all possible matches but no more than necessary), or just examining the string in some other way. But I'm curious.
FWIW, with a near-equivalent JavaScript testcase, Safari 12.0 on OSX works as I'd expect, with only a very small variation between the three searches (which I'm attributing to random factors) and no obvious pattern:
For the avoidance of doubt, I retested with a regex as simple as ^what
and got the same results. Might update the above examples later for coherence if I can work up the motivation. :)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…