GolangNote

Golang笔记

Golang 字符串 Split、index和 LastIndex 的性能

Permalink

对一个字符串做分割操作,可以用 SplitIndex 来实现,这里对这两者的性能做一个简单比较。

Golang 字符串 Split 和 index 的性能

应用场景,对一些特定字符串: ip:port,取 字符 : 之前的内容

Split

Go: Split
1
2
3
4
5
6
7
8
9
func Benchmark_split(b *testing.B) {
	b.ResetTimer()
	defer b.StopTimer()
	for i := 0; i < b.N; i++ {
		for _, s := range ss {
			_ = strings.Split(s, ":")[0]
		}
	}
}

Index

Go: Index
1
2
3
4
5
6
7
8
9
10
11
12
13
14
func Benchmark_index(b *testing.B) {
	b.ResetTimer()
	defer b.StopTimer()
	for i := 0; i < b.N; i++ {
		for _, s := range ss {
			index := strings.Index(s, ":")
			if index == -1 {
				_ = s
			} else {
				_ = s[:index]
			}
		}
	}
}

LastIndex

Go: LastIndex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
func Benchmark_index2(b *testing.B) {
	b.ResetTimer()
	defer b.StopTimer()
	for i := 0; i < b.N; i++ {
		for _, s := range ss {
			index := strings.LastIndex(s, ":")
			if index == -1 {
				_ = s
			} else {
				_ = s[:index]
			}
		}
	}
}

测试

Bash: go test
1
go test -v split_test.go -bench "Benchmark" -benchmem

测试的字符串

Go: string
1
2
3
4
5
var ss = []string{
	"127.0.0.1:1092",
	"192.168.1.1",
	":8080",
}

测试结果

plaintext: 测试结果
1
2
3
4
5
6
7
8
9
goos: darwin
goarch: amd64
cpu: Intel(R) Core(TM) i7-4870HQ CPU @ 2.50GHz
Benchmark_split
Benchmark_split-8    	 5861836	       201.1 ns/op	      80 B/op	       3 allocs/op
Benchmark_index
Benchmark_index-8    	66389178	        18.14 ns/op	       0 B/op	       0 allocs/op
Benchmark_index2
Benchmark_index2-8   	51777555	        22.92 ns/op	       0 B/op	       0 allocs/op

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

Related articles

Golang 把cookie 字符串解析为cookie 结构

在做爬虫时有时候会遇到需要带已登录的 cookie 请求,这个时候最简单的方法是在浏览器登录后,在开发者面板找到cookie 字符串,然后拷贝粘贴。这就面临一个问题需要把cookie 字符串解析成Go 语言 cookie 结构体。...

Write a Comment to "Golang 字符串 Split、index和 LastIndex 的性能"

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