Go Code Smells — Smells Like Ruby/Python/Perl/PHP
Go Code Smells — Smells Like Ruby/Python/Perl/PHP
This is a common pattern that I see in Go code written by somebody who has Ruby/Python/Perl/PHP background.
In those aforementioned languages, it’s very common to take a piece of string, and apply regular expression or straightforward string replacements to munge it.
In Go, regular expressions exist, and are useful, but they are generally not as performant as other tools that are available in the language. In particular, repeated instantiation of *regexp.RegExp objects are just not worth it for anything except for throw away scripts:
func MungeString(src string) string {
re1 := regexp.MustCompile(`...`)
src = re1.ReplaceAllString(src, repl)re2 := regexp.MustCompile(`...`)
src = re2.ReplaceAllString(src, repl)
...
return src
}
If you are going to use *regexp.RegExp, you pre-compile them, and reuse them.
But wait! I would even go further and say that in most cases, you don’t even need regular expressions. It makes sense to use regular expressions in the aforementioned languages because they are more tightly coupled with the language itself (especially Perl), but if you just want to build a string do consider doing things in separate steps.
For example, say, depending on some condition, you want to inject pieces of string in the middle of the text.
Preamble
// say, this is where you want to inject some text (and pretend this line does not exist)
Body
In Perl it’s very natural to do this:
if ($condition) {
$str =~ s/(?=\nBody)/TextToInject/;
}But in Go, it’s going to be far more performant if you separate that logic out of building the original string:
var out bytes.Buffer
printPreamble(&out) // "Preamble\n" is printed to out
injectString(&out) // Inject that text
printBody(&out) // "Body\n" is printed to out
out.String() // get the result
Obviously, this a contrived example. There will be different patterns, but my point is: if you feel like doing string replacements when you’re just building a string in Go, think twice.
Happy hacking.
—
Update:
Noted. I’m not a Python programmer.