DEV Community

Discussion on: Concatenate strings in golang a quick benchmark : + or fmt.Sprintf ?

Collapse
 
titogeorge profile image
Tito George

In my case join wins by a long margin, cant figure out whats wrong.

var word = []string{"9b4e6f7f-1c37-4730-9417-e23747572608", "9b4e6f7f-1c37-4730-9417-e23747572608", "9b4e6f7f-1c37-4730-9417-e23747572608", "9b4e6f7f-1c37-4730-9417-e23747572608", "9b4e6f7f-1c37-4730-9417-e23747572608", "9b4e6f7f-1c37-4730-9417-e23747572608"}

func BenchmarkStringsSprint(b *testing.B) {
    b.ReportAllocs()
    values := ""
    for i := 0; i < b.N; i++ {
        for _, s := range word {
            values = fmt.Sprintf("%s %s", values, s)
        }
    }
}

func BenchmarkStringsJoin(b *testing.B) {
    b.ReportAllocs()
    for i := 0; i < b.N; i++ {
        values := strings.Join(word, " ")
        _ = values
    }
}

func BenchmarkBuilder(b *testing.B) {
    b.ReportAllocs()
    for n := 0; n < b.N; n++ {
        var b strings.Builder
        for _, s := range word {
            b.WriteString(s)
            b.WriteByte(' ')
        }
        _ = b.String()
    }
}
Enter fullscreen mode Exit fullscreen mode

Join has less allocs as well

BenchmarkStringsSprint
BenchmarkStringsSprint-16                      10000       2180843 ns/op    13404016 B/op         32 allocs/op
BenchmarkStringsJoin
BenchmarkStringsJoin-16                     10398318           139.0 ns/op       224 B/op          1 allocs/op
BenchmarkBuilder
BenchmarkBuilder-16                          4303065           247.6 ns/op       720 B/op          4 allocs/op
Enter fullscreen mode Exit fullscreen mode