SoFunction
Updated on 2025-03-01

Comparative analysis of golang string splicing methods

String stitching

There are several ways to splice strings

  • Plus sign +
  • This method is officially recommended

Create a new unit test file string_test.go

package test
import (
    "bytes"
    "fmt"
    "strings"
    "testing"
)
func BenchmarkFmtSprintf(b *) {
    for i := 0; i < ; i++ {
        s := ("%s%s", "abcdefghijklmnopqrstuvwxyz", "123456789")
        (s)
    }
}
func BenchmarkAdd(b *) {
    for i := 0; i < ; i++ {
        s := "abcdefghijklmnopqrstuvwxyz" +"123456789"
        (s)
    }
}
func BenchmarkStringsJoin(b *) {
    for i := 0; i < ; i++ {
        s := ([]string{"abcdefghijklmnopqrstuvwxyz","123456789"}, "")
        (s)
    }
}
func BenchmarkBuffer(b *) {
    for i := 0; i < ; i++ {
        buf := {}
        ("abcdefghijklmnopqrstuvwxyz")
        ("123456789")
        (())
    }
}
func BenchmarkBuilder(b *) {
    for i := 0; i < ; i++ {
        builder := {}
        ("abcdefghijklmnopqrstuvwxyz")
        ("123456789")
        (())
    }
}

implement

go test string_test.go -benchmem -bench=".*"

result:

BenchmarkFmtSprintf-4 2962962 400.6 ns/op 112 B/op 3 allocs/op
BenchmarkAdd-4 6629833 207.7 ns/op 64 B/op 2 allocs/op
BenchmarkStringsJoin-4 4255318 291.6 ns/op 112 B/op 3 allocs/op
BenchmarkBuffer-4 2948402 368.3 ns/op 176 B/op 4 allocs/op
BenchmarkBuilder-4 3149605 352.1 ns/op 160 B/op 4 allocs/op
PASS
ok command-line-arguments 8.219s
Execution efficiency sort+>join>>>

Create a new unit test file string2_test.go

package test
import (
    "bytes"
    "fmt"
    "strings"
    "testing"
)
func BenchmarkAdd2(b *) {
    s:= "abcdefghijklmnopqrstuvwxyz"
    for i := 0; i < ; i++ {
        s += "abcdefghijklmnopqrstuvwxyz"
    }
    (s)
}
func BenchmarkBuffer2(b *) {
    buf := {}
    for i := 0; i < ; i++ {
        ("abcdefghijklmnopqrstuvwxyz")
    }
    (())
}
func BenchmarkBuilder2(b *) {
    builder := {}
    for i := 0; i < ; i++ {
        ("abcdefghijklmnopqrstuvwxyz")
    }
    (())
}

implement

go test string2_test.go -benchmem -bench=".*"

result:

goos: windows
goarch: amd64
cpu: Intel(R) Core(TM) i7-6500U CPU @ 2.50GHz
BenchmarkAdd2-4 10000 101400 ns/op 133806 B/op 1 allocs/op
BenchmarkBuffer2-4 15974260 79.25 ns/op 145 B/op 0 allocs/op
BenchmarkBuilder2-4 17142856 59.38 ns/op 189 B/op 0 allocs/op
PASS
ok command-line-arguments 4.912s
Execution efficiency sorting: >> Add sign
And the memory size and number of times are better than the plus sign

Summarize

From this we can see that in different usage scenarios, different splicing methods should be used, and the plus sign should be used in some simple splicing strings is simple and efficient, and it is recommended to and in complex splicing scenarios.

The above is the detailed content of the comparison and analysis of golang string splicing methods. For more information about golang string splicing, please follow my other related articles!