package mypkg
import (
"strconv"
)
func GenMap() map[string]string {
map1 := make(map[string]string)
for i := 0; i < 10; i++ {
map1["key"+strconv.Itoa(i)] = "value" + strconv.Itoa(i)
}
return map1
}
func GenSlice() []string {
slice1 := make([]string, 100)
for i := 0; i < 10; i++ {
slice1 = append(slice1, "value"+strconv.Itoa(i))
}
return slice1
}
func ReadFromMap(map1 map[string]string) bool {
//for k, _ := range map1 {
// if k == "key80" {
// return true
//fmt.Println(map1["key80"])
// }
//}
if _, exist := map1["key8"]; exist {
return true
}
return false
}
func ReadFromSlice(slice1 []string) bool {
for _, v := range slice1 {
if v == "value8" {
return true
//fmt.Println(slice1[k])
}
}
return false
}
test:
package mypkg
import "testing"
func BenchmarkReadFromMap(b *testing.B) {
map1 := GenMap()
for i := 0; i < b.N; i++ {
ReadFromMap(map1)
}
}
func BenchmarkReadFromSlice(b *testing.B) {
slice1 := GenSlice()
for i := 0; i < b.N; i++ {
ReadFromSlice(slice1)
}
}
结果:
BenchmarkReadFromMap-8 47380273 23.4 ns/op
BenchmarkReadFromSlice-8 14016381 84.7 ns/op
比较map是O(1),而且app信息初始化的时候不是map slice各保存一份了吗,从token获取app_id,就能直接map[app_id]取内容了,没必要循环了。
service那个得循环,因为并不知道servicename