gitee.com/sy_183/go-common@v1.0.5-0.20231205030221-958cfe129b47/maps/unsafe/unsafe_test.go (about) 1 package unsafe 2 3 import ( 4 "gitee.com/sy_183/go-common/unit" 5 "strconv" 6 "strings" 7 "testing" 8 "unsafe" 9 ) 10 11 func BenchmarkMapRange(b *testing.B) { 12 m := make(map[string]string) 13 for i := 0; i < unit.MeBiByte; i++ { 14 m["key-"+strconv.Itoa(i)] = "value-" + strconv.Itoa(i) 15 } 16 b.ResetTimer() 17 for i := 0; i < b.N; i++ { 18 for k, v := range m { 19 if !strings.HasPrefix(k, "key-") { 20 b.Fatal(k) 21 } 22 if !strings.HasPrefix(v, "value-") { 23 b.Fatal(v) 24 } 25 if k[len("key-"):] != v[len("value-"):] { 26 b.Fatal(v) 27 } 28 } 29 } 30 b.StopTimer() 31 } 32 33 func BenchmarkMapIter(b *testing.B) { 34 m := make(map[string]string) 35 for i := 0; i < unit.MeBiByte; i++ { 36 m["key-"+strconv.Itoa(i)] = "value-" + strconv.Itoa(i) 37 } 38 b.ResetTimer() 39 for i := 0; i < b.N; i++ { 40 for it := NewIter(m); it.Has(); it.Next() { 41 k, v := it.Key(), it.Value() 42 if !strings.HasPrefix(k, "key-") { 43 b.Fatal(k) 44 } 45 if !strings.HasPrefix(v, "value-") { 46 b.Fatal(v) 47 } 48 if k[len("key-"):] != v[len("value-"):] { 49 b.Fatal(v) 50 } 51 } 52 } 53 b.StopTimer() 54 } 55 56 func BenchmarkRuntimeIter(b *testing.B) { 57 m := make(map[string]string) 58 for i := 0; i < unit.MeBiByte; i++ { 59 m["key-"+strconv.Itoa(i)] = "value-" + strconv.Itoa(i) 60 } 61 b.ResetTimer() 62 for i := 0; i < b.N; i++ { 63 mi := any(m) 64 hi := new(iter) 65 mapiterinit(*(*unsafe.Pointer)(unsafe.Pointer(&mi)), *(*unsafe.Pointer)(unsafe.Pointer(&m)), hi) 66 for ; hi.key != nil; mapiternext(hi) { 67 k, v := *(*string)(hi.key), *(*string)(hi.elem) 68 if !strings.HasPrefix(k, "key-") { 69 b.Fatal(k) 70 } 71 if !strings.HasPrefix(v, "value-") { 72 b.Fatal(v) 73 } 74 if k[len("key-"):] != v[len("value-"):] { 75 b.Fatal(v) 76 } 77 } 78 } 79 b.StopTimer() 80 }