Why std::regex Loses to Launching Python
On a 5.6 MB log corpus, libstdc++'s std::regex takes 490 ms to find every e-mail address. Starting a fresh Python interpreter from C++, doing the same search there and piping the results back takes 113 ms.
This post explains the benchmark behind that number and the design decisions that make it possible.
The claim
This started as a comment. Nikolai Kutiavin shared a snippet that used std::regex, and I replied that I would avoid it anywhere performance matters. "Trust me, it's slow" is a weak benchmark, so I wrote a real one and posted the headline numbers on LinkedIn.
The comparison is deliberately unfair to C++. The main opponent is not RE2 or PCRE2 with a JIT. It is Python's re module, reached three ways: called from Python, called through an embedded interpreter, and called by spawning a whole new python3 process per search.
If std::regex loses to the last one, the problem is not a missing micro-optimization.
It loses to the last one on all five workloads.
The benchmark
The corpus is 60,000 synthetic lines, 5.6 MB, generated with a fixed seed. Half are access log lines and half are free text messages, about 40% of which contain an e-mail address:
114.71.52.44 - dave [2025-02-01T23:17:15] "GET /request/connection/handled/table" 301 750800
2025-12-18 13:14:28 connection frank.timeout78@database.io flush finished session critical error compaction table critical shardFive patterns live in one patterns.txt that every contender reads, so nobody gets a friendlier regex:
Workload | Pattern | What it stresses |
parse_line | ^(\d+\.\d+\.\d+\.\d+) - (\w+) \[(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}:\d{2})\] "(GET|POST|PUT|DELETE) (\S+)" (\d{3}) (\d+)$ | Anchored full match with 8 capture groups, once per line |
find_emails | [A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,} | Unanchored search that starts with a greedy character class |
alternation | error|warning|critical|timeout | Four literal alternatives, 64,865 hits |
replace_dates | \d{4}-\d{2}-\d{2} | Search and replace over the whole text |
no_match_scan | zzz[0-9]+qqq | A per-line search that never matches |
All C++ contenders are timed by Google Benchmark through one shared helper. Every workload runs exactly 100 timed passes, and the reported figure is their mean wall time. Wall time matters here: the popen contenders spend their time in a child process, which CPU time would not see.

Every workload returns a checksum: a match count, a summed capture length, or an output size. All four contenders produce identical checksums on all five workloads (12,079 e-mails, for example), so they are doing the same work.
Four contenders
1. C++ with std::regex
This is the version a careful C++ programmer would write. The corpus is loaded and the patterns are compiled before timing starts. Matching runs over std::string_view, so no strings are copied. The patterns are compiled with std::regex::optimize.

The timed workloads are lambdas on top of that. Here are the e-mail search and the log-line parse:

Built with GCC 16.2 at -O2 against libstdc++.
2. Python calling re
The baseline is the same five workloads in plain Python 3.14. File IO and re.compile happen at import, and the functions do only regex work. The patterns are compiled with re.ASCII.

The timing uses the standard library's timeit, with the same 100 passes and the same mean:

3. C++ calling re through embedded CPython
The third contender links libpython, imports the same workloads.py, and calls its functions through the C API. The timing is done by Google Benchmark around the call, through the same bench::add as the std::regex version.

4. C++ spawning a Python process
The last contender is the one built for shock value. For every single pass, C++ calls popen("python3 worker.py find_emails") and reads the matches back through a pipe:

The clock covers everything std::regex was excused from: forking a shell, starting the interpreter, reading the 5.6 MB corpus, compiling the pattern, matching, and writing the actual matches (not a count) back to the parent. A startup_only workload that does everything except the regex work measures that fixed overhead at about 27 ms.
Results

The two in-process Python bars are close everywhere, so the measurement does not depend on who holds the stopwatch. std::regex is 2x to 19x slower than Python's re depending on the workload. The popen bar pays about 27 ms of process startup and file IO on every pass and still finishes ahead of std::regex on four workloads. It loses only the log-line parse, 59 ms to 53 ms, where std::regex is at its best and the startup cost is half the total.
Reading the results
The gap is not constant, and the way it varies says where the time goes.
Search that never matches: about 19x. Python's engine sees that any match must start with the literal zzz and scans for it. libstdc++ runs its full state machine from every position of every line. It also builds a fresh executor and result vector for each of the 60,000 regex_search calls.
Four-word alternation: about 6x. At every position libstdc++ tries each branch in turn, pushing a backtrack frame per branch. Nearly every position fails all four.
Find all e-mails: about 6x. The pattern starts with a greedy class that matches most of the text. Both engines consume a whole word, fail to find @, give the characters back one at a time, then start again one character later. The work is the same shape on both sides. The cost per step is not.
Parse log line: about 3x. The pattern is anchored, so there is one attempt per line and almost no backtracking. This is close to the pure per-character cost of the two engines, and it is the best case for std::regex.
Replace dates: about 2x. Building a 5.4 MB output string costs both sides the same, which dilutes the matching gap.
The important detail is that Python's re is not a clever engine. It is a backtracking matcher, the same family as libstdc++'s default. It has no DFA, no JIT and no SIMD. It wins because it is a tight bytecode interpreter written in C over a flat array of code units, with a handful of basic optimizations such as literal-prefix scanning and single-character repeat loops. So this benchmark does not show that C++ needs a smarter algorithm. It shows that std::regex is far from what a plain, competent implementation of the same algorithm achieves.
The popen column makes the same point in a different way. Subtract its fixed cost of about 27 ms and it tracks native Python closely. Process creation is cheap next to what std::regex spends matching, except on the log-line parse, where the matching itself takes only 53 ms.
Put together, my reading of these numbers is blunt. Backtracking is a slow algorithm to begin with, and std::regex runs it with almost none of the optimizations that let Python's equally plain engine get away with it. That is the frustrating part, because C++ is the language best placed to do this well. Patterns can be compiled at build time, matching can run over std::string_view with no allocation, and the inner loops can be flat, inlined and vectorized. The implementation uses almost none of it.
It also cannot start using it now. The first implementation shipped as templates in headers, so its layout became part of the ABI, and every later release has had to stay compatible with that first design. The sections below go through the details. In my opinion the conclusion is that patching is the wrong goal: it would be better to deprecate std::regex, remove it, and start over with a new design. In my personal view we can go with https://github.com/hanickadot/compile-time-regular-expressions
its a great compile time library that works much better then what we get today but more about this in the next post.
A faster engine behind the same pipe
Python's re is a plain backtracker. The obvious next question is what happens when the spawned process has a fast engine. I added two more contenders, both on PCRE2 with its JIT compiler, which turns the pattern into machine code:
PHP 8.5. Its preg_* functions run on PCRE2 10.49, with the JIT on by default.
Python with the pcre2 package (0.7.1, PCRE2 10.47) in place of re, compiled with jit=True.

The C++ side did not change. bench_popen takes the worker command as its argument, so the same binary that ran python3 worker.py now runs php worker.php.

Spawning PHP beats in-process std::regex on all five workloads, by 1.3x on the log-line parse and by 14x on the e-mail search. PHP also starts faster than Python: its startup_only pass takes about 18 ms against Python's 27 ms. All checksums match the other contenders.
Python on PCRE2 is less clear-cut. Spawned, it beats std::regex on four workloads and loses the log-line parse, 94 ms to 53 ms. The in-process numbers show why:
Workload, in process, ms | Python re | Python pcre2 | PHP preg |
Find all e-mails | 89.1 | 13.3 | 9.4 |
4-word alternation | 35.2 | 24.2 | 7.0 |
Replace dates | 61.9 | 9.1 | 6.2 |
Search, never matches | 5.0 | 25.1 | 2.2 |
Parse log line | 18.6 | 52.2 | 8.9 |
On the e-mail search and the date replacement, PCRE2's JIT is about 7x faster than re. On the workloads that cross the binding many times, it is not. The alternation yields 64,865 match objects and gains only 1.5x. The two per-line workloads make 60,000 calls each and come out slower than re. A trivial one-character search over the same 60,000 lines costs about 23 ms through pcre2 and 4 ms through re, so the time goes to the binding's per-call overhead and not to matching. PHP runs the same engine with a thin call path and has no such penalty.
One more binding detail affected the result. With this package, fullmatch ran no faster with the JIT on than off, and took about twice as long as search on the log-line parse. The pattern is already anchored with ^ and $, so the benchmark uses search there.
The engine matters, and so does the path to it. std::regex has both problems at once: a slow engine and an interface that adds cost to every call.
Why std::regex is slow
Backtracer
We have already discussed it when we discussed the results backtracers are not the best way to implement matching algorithms, they do the job but alas they are slow.
The interface forces generality on every character
std::basic_regex is a template over a character type and a traits class. The traits object owns a std::locale, and the standard routes case folding, collation, character classes and range checks through it. A user may supply their own traits. An engine therefore cannot assume that a-z is a contiguous byte range or that \d is ten fixed values. It has to ask.
libstdc++ represents every character test in the compiled automaton as a type-erased callable:
// bits/regex_automaton.h
using _Matcher = std::function<bool (_CharT)>;Every character the engine examines costs an indirect call through std::function. For char, the bracket matcher behind that call caches its answers in a 256-entry table, so the locale is not consulted each time. The call itself remains, and the compiler cannot inline through it. Alo we should remember that std::function has went a long way but it still has a big overhead so our indirect call is not the same as just calling a function.
Results allocate
std::match_results is a container of sub_match objects with its own allocator. Every search sizes it for the pattern's capture groups, and the executor keeps its own vectors of partial results and repeat counters. std::regex_iterator stores a full match_results inside itself. None of this can be skipped when the caller only wants to know whether a line matches, as in our no_match_scan workload:
The optimize flag is a hint with nothing behind it
Our loader compiles every pattern with std::regex::ECMAScript | std::regex::optimize. The standard describes optimize as a request to prefer matching speed over construction speed. In the GCC 16 headers the flag is defined in regex_constants.h and re-exported by basic_regex, and no other regex header reads it. Passing it changes nothing.
Why it cannot simply be fixed
Every class involved is a template defined in a header: basic_regex, match_results, the compiled automaton, the executor. Their code is instantiated inside each program that uses them, and their layouts are baked into every binary already built. A standard library that keeps ABI compatibility cannot change what a compiled std::regex object contains without breaking programs that pass one across a library boundary.
That leaves little room. A vendor can tune code inside the existing layout, and GCC's move to an explicit frame stack is an example. A vendor cannot replace the automaton with a compact bytecode or a lazy DFA, because the automaton's type is part of the object.
The standard has the same problem one level up. The traits parameter, the locale hooks and the six grammars are all in use. Removing any of them breaks conforming code, and keeping them keeps the cost. This is why the realistic proposals in this area add a new facility instead of repairing the old one, and why the usual advice is to use a different library.
And as i have already mentioned IMHO opinion i would like to see std::regex deprecated and then replaced by a different implementation or a different library.
In conclusion
std::regex is not the right tool if you want regular expressions in C++. It is slow, and it is implemented in a very unoptimized way. Always look at what you actually need first: maybe the job belongs in a different language. If it really has to be C++, I would suggest not calling popen on PHP :) and finding a different C++ library instead.
Next time we will explore libraries such as Boost.Regex and CTRE, and show how they differ from each other, both conceptually and on the clock.


