Golang slice 和 map 的查询性能比较

下面是 Golang slice 和 map 的查询性能比较代码

package main

import (
	"fmt"
	"math/rand"
	"time"
)

const maxSize = 50
const tests = 20000000
const findMult = 1 //9999999999 // 100 = 1% hit rate, 1 = 100% hit rate.

type lst []int

func (l lst) has(xxxx int) bool {
	for _, i := range l {
		if i == xxxx {
			return true
		}
	}
	return false
}

type mp map[int]struct{}

func (m mp) has(xxxx int) bool {
	_, ok := m[xxxx]
	return ok
}

func main() {
	rand.Seed(time.Now().UnixNano())

	for size := 1; size < maxSize; size++ {
		l := make(lst, 0, size)
		m := make(mp, size)
		for i := 0; i < size; i++ {
			e := rand.Int()
			l = append(l, e)
			m[e] = struct{}{}
		}

		found := 0
		start := time.Now()
		for x := 0; x < tests; x++ {
			xxxx := rand.Intn(size * findMult)
			if l.has(xxxx) {
				found++
			}
		}
		sliceDuration := time.Now().Sub(start)

		start = time.Now()
		for x := 0; x < tests; x++ {
			xxxx := rand.Intn(size * findMult)
			if m.has(xxxx) {
				found++
			}
		}
		mapDuration := time.Now().Sub(start)

		// Do something with found so it doesn't get optimized away.
		if found > 0 {
			rand.Int()
		}

		fmt.Printf("%d\t%v\n", size, sliceDuration-mapDuration)
	}
}

输出:

1	-209.706862ms
2	-286.768577ms
3	-253.643371ms
4	-184.176088ms
5	-188.898868ms
6	-194.644208ms
7	-113.719066ms
8	-501.892168ms
9	-34.573439ms
10	-380.242983ms
11	-216.931934ms
12	-631.616472ms
13	-135.392189ms
14	-229.107952ms
15	-114.9351ms
16	-373.97338ms
17	-287.007278ms
18	-34.734517ms
19	-237.892748ms
20	-222.025115ms
21	-140.869821ms
22	13.382928ms
23	-341.238616ms
24	-281.6694ms
25	70.841324ms
26	63.31161ms
27	-179.818415ms
28	-30.357644ms
29	39.261291ms
30	-50.066403ms
31	-75.68084ms
32	113.281835ms
33	119.597633ms
34	222.476972ms
35	-89.222024ms
36	95.265413ms
37	164.569075ms
38	150.392782ms
39	247.403261ms
40	365.580116ms
41	284.544515ms
42	275.936162ms
43	330.8626ms
44	428.790859ms
45	94.745088ms
46	388.334553ms
47	189.708983ms
48	387.604493ms
49	308.960719ms

结论:

25 个元素以下的用slice 性能比map 好

摘自 "Slice vs map for set in golang" https://blog.dubbelboer.com/2015/08/15/slice-vs-map.html 23

Relative Articles
本文网址: https://www.golangnote.com/topic/224.html (转载注明出处)
关于GolangNote:记录在工作中使用golang 遇到、面临的相关问题及解决方法。如果你在这里获得一些知识或信息,解决你的编程问题,请考虑捐赠给不幸的人或者你喜欢的慈善机构,除捐赠外,种植树木、志愿服务或减少排碳的行为也很有益处。