DEV Community

Cover image for The fastest way to concatenate strings in Golang
Shubham Chadokar
Shubham Chadokar

Posted on

3

The fastest way to concatenate strings in Golang

As a developer, we should be aware of all the available ways to implement a solution. This gives us the edge to implement a solution as per the needs.

In this short tutorial, you will learn multiple ways to concatenate a string and which is the fastest.

We will add benchmark testing, to analyse the performance of the function. The results may vary for you due to the machine.

Using Plus (+) Operator

The plus operator is not only used for integers and float but it can be used to concatenate strings, provided the operants are of string type.

// file: main.go
package main

import "fmt"

func main() {
    fmt.Println(plusOperator())
}

func plusOperator() string {
    s1 := "practice"
    s2 := "go"

    return (s1 + s2)
}
Enter fullscreen mode Exit fullscreen mode

Benchmark Test

// file: main_test.go
package main

import "testing"

func BenchmarkPlusOperator(b *testing.B) {
    for i := 0; i < b.N; i++ {
        plusOperator()
    }
}

Enter fullscreen mode Exit fullscreen mode

Output

~ go test -bench=.
goos: darwin
goarch: arm64
pkg: cb/practicegocode
BenchmarkPlusOperator-11     118339720            10.23 ns/op
PASS
ok  
Enter fullscreen mode Exit fullscreen mode

Using Append (+=) Operator

The append operator appends one string to another.

// file: main.go
package main

func main {
...

func appendOperator() string {
    s1 := "practice"
    s2 := "go"

    s1 += s2
    return s2
}
Enter fullscreen mode Exit fullscreen mode

Benchmark Test

// file: main_test.go
package main

import "testing"

func BenchmarkAppendOperator(b *testing.B) {
    for i := 0; i < b.N; i++ {
        appendOperator()
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

~ go test -bench=.
goos: darwin
goarch: arm64
pkg: cb/practicegocode
BenchmarkAppendOperator-11   64080028             17.60 ns/op
PASS
ok  
Enter fullscreen mode Exit fullscreen mode

Using Sprintf function

The fmt.Sprintf function is available in fmt package. This should be only used when you have to format a string of different data types or in a certain format.

// file: main.go
package main

func main() {
...

func sprintf() string {
    s1 := "practice"
    s2 := "go"

    return fmt.Sprintf("%s%s", s1, s2)
}
Enter fullscreen mode Exit fullscreen mode

Benchmark Test

// file: main_test.go
package main

import "testing"

func BenchmarkSprintfOperator(b *testing.B) {
    for i := 0; i < b.N; i++ {
        sprintf()
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

~ go test -bench=.
goos: darwin
goarch: arm64
pkg: cb/practicegocode
BenchmarkSprintfOperator-11     16939860          70.79 ns/op
PASS
ok  
Enter fullscreen mode Exit fullscreen mode

Using strings.Builder

The strings.Builder method appends the bytes of s1 and s2 strings to the str bytes.

// file: main.go
package main

func main() {
...

func stringBuilder() string {
    s1 := "practice"
    s2 := "go"

    var str strings.Builder
    str.WriteString(s1)
    str.WriteString(s2)

    return str.String()
}
Enter fullscreen mode Exit fullscreen mode

Benchmark Test

// file: main_test.go
package main

import "testing"

func BenchmarkStringsBuilderOperator(b *testing.B) {
    for i := 0; i < b.N; i++ {
        stringsBuilder()
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

~ go test -bench=.
goos: darwin
goarch: arm64
pkg: cb/practicegocode
BenchmarkStringsBuilderOperator-11   42873091    26.40 ns/op
PASS
ok  
Enter fullscreen mode Exit fullscreen mode

Final Test

Lets run all the benchmark tests together.

Output

BenchmarkPlusOperator-11                115559880 10.13 ns/op
BenchmarkAppendOperator-11              62112871  17.74 ns/op
BenchmarkSprintfOperator-11             16762341  72.46 ns/op
BenchmarkStringsBuilderOperator-11      45078675  26.17 ns/op
Enter fullscreen mode Exit fullscreen mode

Conclusion

The + operator is the fastest way to concatenate strings and fmt.Sprintf is the slowest.

  <----------------Fastest--------------------
  +  >  +=  >  strings.Builder  >  fmt.Sprintf
  ----------------Slowest--------------------> 
Enter fullscreen mode Exit fullscreen mode

You can also watch this tutorial

You can connect with me at:
Dev.to
YouTube Channel
Personal Blog
Linkedin
Twitter


Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay