Loading
Go Lang

Optimizing String Concatenation in Go

golang and strings

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.

String concatenation without strings.Joins.
String concatenation without strings.Joins.

String concatenation using strings.Joins.

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!

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close