GolangNote

Golang笔记

Golang 合并byte 的性能比较

Permalink

Golang 合并 byte 的性能比较,选择比较快的方式合并 byte

concat.go

Go: 合并 byte
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package concat

func concatCopyPreAllocate(slices [][]byte) []byte {
    var totalLen int
    for _, s := range slices {
        totalLen += len(s)
    }
    tmp := make([]byte, totalLen)
    var i int
    for _, s := range slices {
        i += copy(tmp[i:], s)
    }
    return tmp
}

func concatAppend(slices [][]byte) []byte {
    var tmp []byte
    for _, s := range slices {
        tmp = append(tmp, s...)
    }
    return tmp
}

concat_test.go

Go: 合并测试
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package concat

import "testing"

var slices = [][]byte{
    []byte("my first slice"),
    []byte("second slice"),
    []byte("third slice"),
    []byte("fourth slice"),
    []byte("fifth slice"),
}

var B []byte

func BenchmarkConcatCopyPreAllocate(b *testing.B) {
    for n := 0; n < b.N; n++ {
        B = concatCopyPreAllocate(slices)
    }
}

func BenchmarkConcatAppend(b *testing.B) {
    for n := 0; n < b.N; n++ {
        B = concatAppend(slices)
    }
}

运行结果

Bash: benchmem
1
2
3
4
5
6
7
$ go test . -bench=. -benchmem
goos: darwin
goarch: amd64
BenchmarkConcatCopyPreAllocate-8   	20000000	        59.2 ns/op	      64 B/op	       1 allocs/op
BenchmarkConcatAppend-8            	10000000	       128 ns/op	     112 B/op	       3 allocs/op
PASS
ok  	_/Users/yourname/tmp/golang/concat	2.683s

第一种 concatCopyPreAllocate 的速度是第二种 concatAppend 的两倍。

Related articles

Write a Comment to "Golang 合并byte 的性能比较"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.16.5 Processed in 0ms