ZetCode

Go Builder

last modified February 25, 2021

Go Builder tutorial shows how to build strings efficiently in Golang with strings.Builder.

We build a string with various write methods such as WriteString or WriteRune. In the end, we return the accumulated string with the String method.

The Builder uses an internal slice to store data.

Go Builder example

The next example uses the strings.Builder to form a message.

simple.go
package main

import (
    "fmt"
    "strings"
)

func main() {

    builder := strings.Builder{}

    builder.WriteString("There")
    builder.WriteString(" are")
    builder.WriteString(" three")
    builder.WriteString(" hawks")
    builder.WriteString(" in the sky")

    fmt.Println(builder.String())
}

We build a message using Builder's WriteString.

$ go run simple.go 
There are three hawks in the sky

The next example builds a string from byte slices.

simple2.go
package main

import (
    "fmt"
    "strings"
)

func main() {

    builder := strings.Builder{}

    data1 := []byte{72, 101, 108, 108, 111}
    data2 := []byte{32}
    data3 := []byte{116, 104, 101, 114, 101, 33}

    builder.Write(data1)
    builder.Write(data2)
    builder.Write(data3)

    fmt.Println(builder.String())
}

The example builds a string with Write.

$ go run simple2.go 
Hello there!

Go Builder - comparing performance

In the next example, we compare the performance of a Builder against a string concatenation with the + operator.

compare.go
package main

import (
    "fmt"
    "strings"
    "time"
)

func main() {
    t0 := time.Now()

    builder := strings.Builder{}
    for i := 0; i < 100_000; i++ {
        builder.WriteString("falcon")
    }

    t1 := time.Now()

    result := ""
    for i := 0; i < 100_000; i++ {
        result += "falcon"
    }

    t2 := time.Now()

    fmt.Println(t1.Sub(t0))
    fmt.Println(t2.Sub(t1))
}

The example benchmarks the efficiency of the two ways of string concatenation; it adds the word falcon hundred thousad times.

$ go run compare.go 
2.232505ms
8.007376273s

As we can see from the output, the Builder is much more efficient.

In this tutorial, we have worked with the strings.Builder in Go.

List all Go tutorials.