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 的两倍。

本文网址: https://golangnote.com/topic/188.html 转摘请注明来源

Related articles

Golang 泛型性能初识

编程时,我们通常需要编写“泛型”函数,其中确切的数据类型并不重要。例如,您可能想编写一个简单的函数来对数字进行求和。Go 直到最近才有这个概念,但最近才添加了它(从1.18版开始)。...

Golang Range 的性能提升Tip

Go 语言里使用 range 可以方便遍历数组(array)、切片(slice)、字典(map)和信道(chan)。这里主要关注他们的性能。...

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

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 1ms