4

下面的测试是否能说明 map 中 key 使用 int 比 string 更有优势

 9 months ago
source link: https://studygolang.com/articles/36451
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

下面的测试是否能说明 map 中 key 使用 int 比 string 更有优势

YuPeng · 26分钟之前 · 30 次点击 · 预计阅读时间 2 分钟 · 大约8小时之前 开始浏览    

func Benchmark_MapKey(b *testing.B) {
    var length = 100000
    var intMap, strMap = make(map[int]bool), make(map[string]bool)
    var intSlice, strSlice = make([]int, length), make([]string, length)
    for i := 0; i < length; i++ {
        intSlice[i] = i
        strSlice[i] = strconv.Itoa(i)
    }
    b.Run("intSlice", func(b *testing.B) {
        for i := 0; i < b.N; i++ {
            _ = intSlice[i%length]
        }
    })
    b.Run("strSlice", func(b *testing.B) {
        for i := 0; i < b.N; i++ {
            _ = strSlice[i%length]
        }
    })
    b.Run("intSet", func(b *testing.B) {
        for i := 0; i < b.N; i++ {
            intMap[intSlice[i%length]] = (i%2 == 0)
        }
    })
    b.Run("intGet", func(b *testing.B) {
        for i := 0; i < b.N; i++ {
            _ = intMap[intSlice[i%length]]
        }
    })
    b.Run("strSet", func(b *testing.B) {
        for i := 0; i < b.N; i++ {
            strMap[strSlice[i%length]] = (i%2 == 0)
        }
    })
    b.Run("strGet", func(b *testing.B) {
        for i := 0; i < b.N; i++ {
            _ = strMap[strSlice[i%length]]
        }
    })
}
goos: windows
goarch: amd64
pkg: xxxxxx
cpu: AMD Ryzen 5 5600G with Radeon Graphics         
Benchmark_MapKey/intSlice-12             745706593             1.595 ns/op           0 B/op           0 allocs/op
Benchmark_MapKey/strSlice-12             755215707             1.596 ns/op           0 B/op           0 allocs/op
Benchmark_MapKey/intSet-12               41379309            26.19 ns/op           0 B/op           0 allocs/op
Benchmark_MapKey/intGet-12               51822198            22.27 ns/op           0 B/op           0 allocs/op
Benchmark_MapKey/strSet-12               36364297            28.10 ns/op           0 B/op           0 allocs/op
Benchmark_MapKey/strGet-12               43037130            27.77 ns/op           0 B/op           0 allocs/op

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK