package main import ( "fmt" "time" ) 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 } } } finish1 := 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("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") } func main(){ //slice查詢是遍歷方式,時間複雜度是O(n), map查詢是hash映射 //當數據量小的時候切片查詢比map快,可是數據量大的時候map的優點就體現出來了 testSlice(testTimeSlice) //999.8µs testMap(testTimeMap) //4.9961ms testSlice(testTimeSlice2) //5.0147ms testMap(testTimeMap2) //3.0003ms }