Performance Tips
Reuse compiled regexps.
Performance Tips is a free Go Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Compilation Has a Cost
Turning a pattern string into a usable regexp takes work. Doing it on every call wastes time, especially in loops or hot paths.
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile("[0-9]+")
fmt.Println(re.MatchString("x9"))
}Compile Once, Reuse Often
The golden rule: compile a pattern once and reuse the *regexp.Regexp. A package-level variable is the usual home.
package main
import (
"fmt"
"regexp"
)
var numRe = regexp.MustCompile("[0-9]+")
func hasNumber(s string) bool {
return numRe.MatchString(s)
}
func main() {
fmt.Println(hasNumber("a1"))
fmt.Println(hasNumber("abc"))
}Avoid Compiling in Loops
Never call MustCompile inside a loop. Compile before the loop and use the same value each iteration.
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile("[a-z]+")
inputs := []string{"go", "123", "rust"}
for _, s := range inputs {
fmt.Println(s, re.MatchString(s))
}
}Regexp Is Safe to Share
A compiled *regexp.Regexp is safe for concurrent use by multiple goroutines. One global instance can serve them all.
package main
import (
"fmt"
"regexp"
)
var re = regexp.MustCompile("go")
func main() {
fmt.Println(re.MatchString("golang"))
}Sometimes strings Is Faster
For a fixed literal substring, strings.Contains beats a regexp. Reach for regexps only when you need real pattern power.
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Contains("hello world", "world"))
}Prefer Anchored Patterns
Anchoring with ^ lets the engine fail fast when the start does not match, instead of scanning the whole string.
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile("^https?://")
fmt.Println(re.MatchString("http://site"))
fmt.Println(re.MatchString("see http://x"))
}Limit Match Counts
When you only need a few matches, pass a small n to the Find-all methods instead of -1 to stop early.
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile("[0-9]+")
fmt.Println(re.FindAllString("1 2 3 4 5", 2))
}Watch Out for Backtracking Patterns
Go's RE2 engine avoids catastrophic backtracking, but overly broad patterns like .* can still scan more than needed. Be specific.
package main
import (
"fmt"
"regexp"
)
func main() {
broad := regexp.MustCompile(".*=.*")
precise := regexp.MustCompile("[a-z]+=[0-9]+")
fmt.Println(broad.MatchString("x=1"), precise.MatchString("x=1"))
}Escape Dynamic Input
If a pattern includes user text, escape it with regexp.QuoteMeta so special characters are treated literally.
package main
import (
"fmt"
"regexp"
)
func main() {
user := "a.b"
re := regexp.MustCompile(regexp.QuoteMeta(user))
fmt.Println(re.MatchString("a.b"))
fmt.Println(re.MatchString("axb"))
}Cache Compiled Patterns
If patterns are built at runtime, store compiled ones in a map keyed by the pattern string to avoid recompiling the same one.
package main
import (
"fmt"
"regexp"
)
var cache = map[string]*regexp.Regexp{}
func get(p string) *regexp.Regexp {
if re, ok := cache[p]; ok {
return re
}
re := regexp.MustCompile(p)
cache[p] = re
return re
}
func main() {
fmt.Println(get("[0-9]+").MatchString("7"))
}Putting It Together
A well-tuned validator compiles once, anchors the pattern, and is shared across all calls.
package main
import (
"fmt"
"regexp"
)
var emailRe = regexp.MustCompile("^[a-z0-9]+@[a-z]+\\.[a-z]+$")
func main() {
fmt.Println(emailRe.MatchString("me@site.com"))
}Quick Check
What is the single most important regexp performance tip?
Recap: Performance Tips
You learned to use regexps efficiently:
- Compile once with
MustCompileand reuse; it is concurrency-safe. - Prefer
stringsfor fixed substrings; anchor patterns; limit match counts. - Escape dynamic input with
QuoteMetaand cache runtime patterns.
package main
import (
"fmt"
"regexp"
)
var re = regexp.MustCompile("^\\d{4}$")
func main() {
for _, s := range []string{"1234", "12"} {
fmt.Println(s, re.MatchString(s))
}
}Frequently asked questions
Is the “Performance Tips” lesson free?
Yes — the full text of “Performance Tips” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.
What will I learn in “Performance Tips”?
Reuse compiled regexps. You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Go Academy?
No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Performance Tips” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Go Academy lesson?
Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- regexp Basics
- Finding and Extracting
- Replacing Text
- Performance Tips