std::regex: Function-Local vs. Static-Local Declaration
Question 13 / 17 • Correct so far: 0 (0 answered)
Regex Per Call
bool isEmail(const std::string& s) {
std::regex re(EMAIL_PATTERN);
return std::regex_match(s, re);
}
int count = 0;
for (const auto& s : TEST_STRINGS)
if (isEmail(s)) ++count; Regex Static
bool isEmail(const std::string& s) {
static const std::regex re(EMAIL_PATTERN);
return std::regex_match(s, re);
}
int count = 0;
for (const auto& s : TEST_STRINGS)
if (isEmail(s)) ++count; Shared test data (shared-setup)
static const std::vector<std::string> TEST_STRINGS = {
"foo@example.com",
"not-an-email",
"bar@domain.org",
"invalid",
"user@test.net",
"also-invalid",
"name@company.io",
"bad-string",
"another@valid.com",
"nope",
};
static const char* EMAIL_PATTERN =
R"([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})"; Which snippet is faster?
Snippet B is faster because constructing a std::regex object is expensive — the pattern must be parsed and compiled into an internal automaton on every call. Declaring the regex as a function-local static means that construction happens exactly once; subsequent calls skip it entirely and proceed straight to the match step, which is orders of magnitude cheaper.
Benchmark results
| Snippet | CPU time / iteration | Speedup |
|---|---|---|
| Regex Per Call | 256 us | 1.0× |
| Regex Static | 1.35 us | 189.6× |
Explore the source
Open in Compiler ExplorerQuiz complete. You can return to the question list to restart and compare.