String Matching — Go Benchmark
Compare string matching approaches in Go.
Finding a substring within a larger string is a common task in software development. Go's standard library provides multiple ways to accomplish this, from strings.Contains to regular expressions. This benchmark demonstrates why simple functions like strings.Contains are universally better for exact substring matching compared to regexp, which has its own compilation and evaluation overhead.
1 CPU
Fastest
Strings ContainsSlowest
Regexp Match String32 CPUs
Fastest
Strings ContainsSlowest
Regexp Match StringStrings Contains
FastestUses strings.Contains(haystack, needle). Under the hood, this implementation often maps directly to architecture-specific assembly (like SIMD instructions), making it incredibly fast and allocation-free for exact literal string matching.
Precompiled Regexp
Compiles the regular expression regexp.MustCompile("challenge") once upfront, and evaluates it in the hot loop using re.MatchString(haystack). This skips the heavy regex compilation cost per operation, but still runs through Go's regular expression engine, making it slower than strings.Contains.
Regexp Match String
SlowestCalls regexp.MatchString("challenge", haystack) inside the loop. This is a classic anti-pattern for hot loops because the regex engine must parse and compile the string into a Regexp object on every single iteration, making it the slowest and most allocation-heavy approach.
Contributors