0Pricing
C++ Academy · Lesson

Performance Notes

Compile patterns wisely.

Compilation Is Expensive

Building a std::regex from a string compiles the pattern, which is costly. The biggest win is to compile once and reuse.

  • Avoid constructing regex inside loops.
  • Compile at startup or on first use.
#include <iostream>
#include <regex>

int main() {
    std::regex p("\\d+");
    std::string inputs[] = {"12", "ab", "99"};
    for (const auto& s : inputs) {
        std::cout << s << ": " << std::regex_match(s, p) << '\n';
    }
    return 0;
}

Reuse a Compiled Pattern

Construct the pattern once outside the loop and reuse it for every input. Rebuilding it each iteration wastes time.

#include <iostream>
#include <regex>
#include <vector>

int main() {
    static const std::regex p("[a-z]+");
    std::vector<std::string> words = {"hello", "WORLD", "cpp"};
    int matches = 0;
    for (const auto& w : words) {
        if (std::regex_match(w, p)) ++matches;
    }
    std::cout << "Matched: " << matches << '\n';
    return 0;
}

All lessons in this course

  1. regex Basics
  2. Capturing Groups
  3. Search and Replace
  4. Performance Notes
← Back to C++ Academy