golang中map和slice的查询速度比较,结果意想不到

来源:互联网 发布:php mysql 长连接 编辑:程序博客网 时间:2024/05/22 10:26

看到标题,第一反应,map肯定秒杀slice啊,我当时也是这么想的,毕竟前者的查询复杂度是O(1),后者是O(n)。


但是,事事难预料哦,用代码来说明问题:

先写两个测试函数

var testTimeSlice=[]string{"aa","bb","cc","dd","ee","aa","zz"}var testTimeMap = map[string]bool{"aa": true, "bb": true, "cc": true, "dd": true, "ee": true, "ff": true, "zz": true}//以上为第一组查询测试数据var testTimeSlice2=[] string{"aa","bb","cc","dd","ee","aa","aa","bb","cc","dd","ee","aa","aa","bb","cc","dd","ee","aa","aa","bb","cc","dd","ee","aa","i","j", "l", "m", "n", "o", "p", "q", "k", "x", "y", "z",    "1", "2", "3", "4", "5", "6", "7", "8", "9", "10","zz"}var testTimeMap2 = map[string]bool{"aa": true, "bb": true, "cc": true, "dd": true, "ee": true, "ff": true, "qq": true,"ww": true, "rr": true, "tt": true, "zz": true, "uu": true, "ii": true,"oo": true, "pp": true, "lk": true, "kl": true, "jk": true, "kj": true,"hl": true, "lh": true, "fg": true, "gfdd": true, "df": true, "fd": true,    "i": true, "j": true, "l": true, "m": true, "n": true, "o": true, "p": true, "q": true, "k": true, "x": true, "y": true, "z": true,    "1": true, "2": true, "3": true, "4": true, "5": true, "6": true, "7": true, "8": true, "9": true, "10": true}//以上为第二组查询测试数据func testSlice(a []string)  {    now:=time.Now()    for j:=0; j < 100000; j++{        for _,v:=range a{            if v=="zz"{                break            }        }    }    finish:=time.Since(now)fmt.Println(finish1)}func testMap(a map[string]bool) {    now:=time.Now()    for j:=0; j < 100000; j++{        if _, ok := a["zz"]; ok {            continue        }    }    finish2:=time.Since(now)    fmt.Println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")    fmt.Println(finish2)    fmt.Println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")}



第一个函数接受一个slice,然后进行十万次查询,第二个函数接受一个map,进行十万次查询。

当用第一组测试数据时,结果如下:

1.0011ms   //Slice查询耗时!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!6.0038ms   //Map查询耗时!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!



用第二组测试数据时,结果如下:

8.0038ms    //Slice查询耗时!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!2.0019ms    //Map查询耗时!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!



现在可以得出结论了,当数据量小的时候,slice的查询速度是比map快的,为什么呢,因为golang的map底层是用hash实现的,既然有hash,那就要做映射,那就有hash函数,这个hash函数的开销千万不要忘记,不要一看到map就只记着O(1)


数据集小,直接遍历查找的开销肯定比hash的开销小。


当数据量上去了,map的优势自然而然就出来了。

原创粉丝点击