0Pricing
Go Academy · Lesson

Performance Tips

Reuse compiled regexps.

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"))
}

All lessons in this course

  1. regexp Basics
  2. Finding and Extracting
  3. Replacing Text
  4. Performance Tips
← Back to Go Academy