字符串拼接在golang中是非常常见的操作,本文介绍几种常用方法并分析各种方法的效率.
拼接
+ 号拼接
+ 号拼接是最常见的方式
var a string = "Hello,"
var b string = "World!"
func Test1() string {
return a + b
}
buffer拼接
bytes 库提供一个结构体 Buffer, Buffer结构允许多次写入[]byte 、string 、rune类型的数据并一次性输出
var a string = "Hello,"
var b string = "World!"
func Test2() string {
var buffer bytes.Buffer
buffer.WriteString(a)
buffer.WriteString(b)
return buffer.String()
}
fmt.Sprint()格式化
fmt 库提供的 SprintX() 系列函数可以返回格式化后的字符串,也可用来做拼接操作
var a string = "Hello,"
var b string = "World!"
func Test3() string {
return fmt.Sprint(a, b)
}
append拼接
字符串的底层是数组,而数组的拼接可以使用 append(),因此可以利用这一特性来进行字符串拼接操作.
var a string = "Hello,"
var b string = "World!"
func Test4() string {
return string(append([]byte(a), []byte(b)...))
}
性能
以上介绍了比较常见的几种拼接方式,但是究竟哪种效率更高呢?下面针对 单次拼接 做一个测试,将上述代码保存为plus.go.
package plus
import (
"bytes"
"fmt"
)
var a string = "Hello,"
var b string = "World!"
func Test1() string {
return a + b
}
func Test2() string {
var buffer bytes.Buffer
buffer.WriteString(a)
buffer.WriteString(b)
return buffer.String()
}
func Test3() string {
return fmt.Sprint(a, b)
}
func Test4() string {
return string(append([]byte(a), []byte(b)...))
}
然后编写测试脚本plus_test.go.
package plus_test
import (
p "plus"
"testing"
)
func BenchmarkTestPlus(b *testing.B) {
for i := 0; i < b.N; i++ {
p.Test1()
}
}
func BenchmarkTestBuffer(b *testing.B) {
for i := 0; i < b.N; i++ {
p.Test2()
}
}
func BenchmarkTestFormat(b *testing.B) {
for i := 0; i < b.N; i++ {
p.Test3()
}
}
func BenchmarkTestAppend(b *testing.B) {
for i := 0; i < b.N; i++ {
p.Test4()
}
}
go test stringplus_test.go -bench=.
- goos: darwin
- goarch: amd64
- BenchmarkTestPlus-8 100000000 22.2 ns/op
- BenchmarkTestBuffer-8 20000000 102 ns/op
- BenchmarkTestFormat-8 10000000 191 ns/op
- BenchmarkTestAppend-8 50000000 26.4 ns/op
+append()bytes.Bufferfmt.Sprint()
分析
+ 与 append()性能分析
++append(a,b)
append()
a,b[]byteappend()[]bytestring
append()+
var a string = "Hello,"
var b string = "World!"
var c = []byte{72, 101, 108, 108, 111, 44}
var d = []byte{87, 111, 114, 108, 100, 33}
func Test1() string {
return a+b
}
func Test5() []byte {
return append(c, d...)
}
append()
- BenchmarkTestPlus-8 100000000 22.0 ns/op
- BenchmarkTestAppend-8 50000000 26.0 ns/op
- BenchmarkTestAppendByte-8 50000000 37.6 ns/op
append()src/builtin/builtin.go
[]slicelencap
append byte性能分析
e,f[]bytea,b
var a string = "Hello,"
var b string = "World!"
var c = []byte{72, 101, 108, 108, 111, 44}
var d = []byte{87, 111, 114, 108, 100, 33}
e := []byte(a)
f := []byte(b)
fmt.Println("c的长度:", len(c), "容量:", cap(c))
fmt.Println("d的长度:", len(d), "容量:", cap(d))
fmt.Println("e的长度:", len(e), "容量:", cap(e))
fmt.Println("f的长度:", len(f), "容量:", cap(f))
输出结果如下:
- c的长度: 6 容量: 6
- d的长度: 6 容量: 6
- e的长度: 6 容量: 32
- f的长度: 6 容量: 32
[]byte()e,fc,dc
切片迁移(拷贝)
[5]int[5]int6,7,8,9,10
2倍
fmt.SprintX()性能分析
fmtinterface{}Sprint()
func Sprint(a ...interface{}) string{}
src/fmt/print.go
// Some types can be done without reflection.
switch f := arg.(type) {
case bool:
p.fmtBool(f, verb)
case float32:
p.fmtFloat(float64(f), 32, verb)
case float64:
p.fmtFloat(f, 64, verb)
case complex64:
p.fmtComplex(complex128(f), 64, verb)
case complex128:
p.fmtComplex(f, 128, verb)
case int:
p.fmtInteger(uint64(f), signed, verb)
case int8:
p.fmtInteger(uint64(f), signed, verb)
case int16:
p.fmtInteger(uint64(f), signed, verb)
case int32:
p.fmtInteger(uint64(f), signed, verb)
case int64:
p.fmtInteger(uint64(f), signed, verb)
case uint:
p.fmtInteger(uint64(f), unsigned, verb)
case uint8:
p.fmtInteger(uint64(f), unsigned, verb)
case uint16:
p.fmtInteger(uint64(f), unsigned, verb)
case uint32:
p.fmtInteger(uint64(f), unsigned, verb)
case uint64:
p.fmtInteger(f, unsigned, verb)
case uintptr:
p.fmtInteger(uint64(f), unsigned, verb)
case string:
p.fmtString(f, verb)
case []byte:
p.fmtBytes(f, verb, "[]byte")
case reflect.Value:
// Handle extractable values with special methods
// since printValue does not handle them at depth 0.
if f.IsValid() && f.CanInterface() {
p.arg = f.Interface()
if p.handleMethods(verb) {
return
}
}
p.printValue(f, verb, 0)
default:
// If the type is not simple, it might have methods.
if !p.handleMethods(verb) {
// Need to use reflection, since the type had no
// interface methods that could be used for formatting.
p.printValue(reflect.ValueOf(f), verb, 0)
}
}
reflect
bytes.Buffer性能分析
WriteString()append()tryGrowByReslice()copy()fmt
func (b *Buffer) WriteString(s string) (n int, err error) {
b.lastRead = opInvalid
m, ok := b.tryGrowByReslice(len(s))
if !ok {
m = b.grow(len(s))
}
return copy(b.buf[m:], s), nil
}
总结
+append()fmt.SpintX()bytes.Buffer