Go Benchmark
Regexp vs Manual String Validation
Precompiled regexp, inline regexp, and hand-rolled string checks compared.
Validating that a string "looks like an email" is a classic task with three common solutions in Go: a regular expression compiled once at package level, the same regexp carelessly compiled inside the hot loop, and a hand-written validator built from strings functions. This benchmark runs all three against the same mix of valid and invalid addresses. Two lessons hide in the chart: compiling a regexp is orders of magnitude more expensive than matching one (never call regexp.MustCompile in a loop), and even a precompiled regexp costs several times more than a few explicit strings.IndexByte checks — the price of the regex engine's generality.
1 CPU
32 CPUs
A hand-rolled validator using strings.IndexByte and strings.LastIndexByte to check the local@domain.tld shape directly. Zero allocations and a handful of byte scans. Less expressive and more code to maintain than a regexp, but for simple shapes on hot paths it is by far the fastest option.
Precompiled Regexp #
Compiles regexp.MustCompile(emailPattern) once before the loop — the idiomatic equivalent of a package-level var emailRe = regexp.MustCompile(...). Each check only pays for running the regex engine's state machine over the input.
Calls regexp.MustCompile(emailPattern).MatchString(...) inside the loop, so every iteration parses the pattern, builds the state machine, and allocates the Regexp object before matching. A surprisingly common mistake — and the chart shows why it matters.
Contributors