Go:for 與 range 的性能比較
func generateWithCap(n int) []int {
rand.Seed(time.Now().UnixNano())
nums := make([]int, 0, n)
for i := 0; i < n; i++ {
nums = append(nums, rand.Int())
}
return nums
}
func BenchmarkForIntSlice(b *testing.B) {
nums := generateWithCap(1024 * 1024)
for i := 0; i < b.N; i++ {
len := len(nums)
var tmp int
for k := 0; k < len; k++ {
tmp = nums[k]
}
_ = tmp
}
}
func BenchmarkRangeIntSlice(b *testing.B) {
nums := generateWithCap(1024 * 1024)
for i := 0; i < b.N; i++ {
var tmp int
for _, num := range nums {
tmp = num
}
_ = tmp
}
}
#####
# go test -bench=IntSlice$ -benchmem .
goarch: amd64
pkg: hello
cpu: Intel(R) Core(TM) i7-8700 CPU @ 3.20GHz
BenchmarkForIntSlice-12 2349 510717 ns/op 3571 B/op 0 allocs/op
BenchmarkRangeIntSlice-12 4588 256757 ns/op 1828 B/op 0 allocs/op
PASS
- 明顯可以看出吴藻,
for
比 range
更高效
- 原因是
range
每次迭代都會(huì)對(duì)迭代值進(jìn)行一次拷貝(value)
- 當(dāng)?shù)嫡純?nèi)存越大,對(duì)性能消耗則越大弓柱,特別是對(duì)
[]struct{}
進(jìn)行迭代時(shí)沟堡!因此通常使用 []*struct{}
進(jìn)行迭代而不是 []struct{}