mynote/go/map 和 slice 索引速度比较.md
2020-06-26 21:29:00 +08:00

89 lines
2.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# golang 中map 和slice 索引速度比较
## 主文件
```go
package main
var max = 100
var Slice = make([]int, max+10)
var Map = make(map[int]int)
func init() {
for i := 0; i < max; i++ {
Slice[i] = i
Map[i] = i
}
}
// 查找算法可以优化,本文对于常用无序查找做比较
func SearchSlice(i int) int {
for _, v := range Slice {
if v == i {
return v
}
}
return -1
}
func SearchMap(i int) int {
return Map[i]
}
```
## 测试文件
```go
package main
import "testing"
func BenchmarkSearchMap(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = SearchMap(i % max)
}
}
func BenchmarkSearchSlice(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = SearchSlice(i % max)
}
}
func BenchmarkSlice(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = Slice[i%max]
}
}
```
## 测试结果
max = 100
```bash
BenchmarkSearchMap-16 94148293 12.7 ns/op 0 B/op 0 allocs/op
BenchmarkSearchSlice-16 49473447 23.6 ns/op 0 B/op 0 allocs/op
BenchmarkSlice-16 187461336 6.46 ns/op 0 B/op 0 allocs/op
```
max = 10000
```bash
BenchmarkSearchMap-16 43147364 27.6 ns/op 0 B/op 0 allocs/op
BenchmarkSearchSlice-16 968623 1159 ns/op 0 B/op 0 allocs/op
BenchmarkSlice-16 187649472 6.42 ns/op 0 B/op 0 allocs/op
```
Max = 1000000
```bash
BenchmarkSearchMap-16 15015690 90.1 ns/op 0 B/op 0 allocs/op
BenchmarkSearchSlice-16 441436 104242 ns/op 0 B/op 0 allocs/op
BenchmarkSlice-16 182620702 6.58 ns/op 0 B/op 0 allocs/op
```
在一些特定优化条件下可以尝试用slice效果会比map好比如把10^6^级的查找优化成3级10^2^查找, 对于一些结构体,可以根据某些特征分类或预先根据特征值排序