by silisili · 5y ago · 0 comments
Anecdotally, this could be a huge win, depending on how often it's called.
A guy I was working with, new to Go, was writing a router config parser and asked why it was so slow.
The first thing I did was moved regexp.Compile from a hot path into a broader scope. It went from something like 40 seconds down to 2 on my machine.
It would probably be a good idea to add performance hints like 'prefer to put static regular expressions in a package variable' in a linter or go vet.
Moving static (at least as much it concerns the loop) expressions out of a loop is one of the most fundamental optimizations a programmer should do when writing code.
IMHO, the stdlib doing implicit memoization is a catastrophe waiting to happen.
I think that handling regexps and caching functions are two composable and orthogonal features that should be handled by two packages/libs/... .
I'd only use a variable when I'm using the same regex multiple times in code, and even then I could still just have the variable be the string.
Last time I had a look the regex cache was pretty small (few hundred entries) and gets completely cleared when full. Might have improved since, but historically it was very simplistic.
I disagree that it’s “proper and good usage” to specify regex inline. It’s fine for many usages but that’s as far as I’d go.
Caveat: I write libraries, not "production" code; my requirements are significantly more strict. One thing I can't do is make assumptions about where my code will run. If you're using my library, and you compile a whole bunch of regexes, they'll evict my regexes from the cache. I don't want the performance of my library to suffer, so I'll keep them in the module scope.