github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/zarray/hashmap_benchmark_test.go (about) 1 //go:build go1.18 2 // +build go1.18 3 4 package zarray_test 5 6 import ( 7 "sync" 8 "sync/atomic" 9 "testing" 10 11 "github.com/sohaha/zlsgo/zarray" 12 ) 13 14 const size = 1 << 12 15 16 func BenchmarkGoSyncSet(b *testing.B) { 17 var m sync.Map 18 b.RunParallel(func(pb *testing.PB) { 19 for pb.Next() { 20 for i := 0; i < size; i++ { 21 m.Store(i, i) 22 } 23 } 24 }) 25 } 26 27 func BenchmarkHashMapSet(b *testing.B) { 28 m := zarray.NewHashMap[int, int]() 29 b.RunParallel(func(pb *testing.PB) { 30 for pb.Next() { 31 for i := 0; i < size; i++ { 32 m.Set(i, i) 33 } 34 } 35 }) 36 } 37 38 func BenchmarkGoSyncGet(b *testing.B) { 39 var m sync.Map 40 for i := 0; i < size; i++ { 41 m.Store(i, i) 42 } 43 var n int64 44 b.ResetTimer() 45 b.RunParallel(func(pb *testing.PB) { 46 for pb.Next() { 47 if atomic.CompareAndSwapInt64(&n, 0, 1) { 48 for pb.Next() { 49 for i := 0; i < size; i++ { 50 m.Store(i, i) 51 } 52 } 53 } else { 54 for pb.Next() { 55 for i := 0; i < size; i++ { 56 j, _ := m.Load(i) 57 if j != i { 58 b.Fail() 59 } 60 } 61 } 62 } 63 } 64 }) 65 } 66 67 func BenchmarkHashMapGet(b *testing.B) { 68 m := zarray.NewHashMap[int, int]() 69 for i := 0; i < size; i++ { 70 m.Set(i, i) 71 } 72 var n int64 73 b.ResetTimer() 74 b.RunParallel(func(pb *testing.PB) { 75 for pb.Next() { 76 if atomic.CompareAndSwapInt64(&n, 0, 1) { 77 for pb.Next() { 78 for i := 0; i < size; i++ { 79 m.Set(i, i) 80 } 81 } 82 } else { 83 for pb.Next() { 84 for i := 0; i < size; i++ { 85 j, _ := m.Get(i) 86 if j != i { 87 b.Fail() 88 } 89 } 90 } 91 } 92 } 93 }) 94 }