I bet that every experienced programmer in this planet, at least once, had come across code issues related with performance, and to make things worse, sometimes it’s not something so obvious to spot! Even a trivial implementation like string concatenation can lead you in the whole nightmare!
With two examples, I will try to show you how you can do better when comes to strings in Go.
Imagine a simple experiment that consists in reading all the arguments passed through a console command. Our goal is to compare what is the performance outcome of string concatenation when using a normal string assignment, versus the function Joins on the Strings package.
To make all of it easier, I shared the code example of string optimization in Go, on my following GitHub repository:
The first example, the NOT optimized one, is quite simple and consist in reading the arguments using the traditional Args variable exported from the package OS.
var s, sep string
for i := 1; i < len(os.Args); i++ {
s += sep + os.Args[i]
sep = " "
}
fmt.Println(s)
As you can notice, we interact over the items available on os.Args and do the concatenation of their values with an empty space, after the first interaction.
Now comes the magic!
fmt.Println(strings.Join(os.Args[1:], " "))
With exactly ONE line you can archive the same result and with better performance, as shown below while running the go test -bench command.
Plus, I would like to share with interesting external resources related with test and benchmark in Go:
That is all!
The thing to learn from this is that even small, eye-missing optimization can give us big problems over heavily accessed applications!