github.com/15mga/kiwi@v0.0.2-0.20240324021231-b95d5c3ac751/ds/set_test.go (about) 1 package ds 2 3 import ( 4 "math/rand" 5 "strconv" 6 "testing" 7 ) 8 9 type Player struct { 10 cid int64 11 name string 12 } 13 14 func BenchmarkKSet(b *testing.B) { 15 count := 1024 << 6 16 slc := make([]*Player, 0, count) 17 mp := make(map[int64]*Player, count) 18 set := NewKSet[int64, *Player](count<<2, func(player *Player) int64 { 19 return player.cid 20 }) 21 players := make([]*Player, 0, count) 22 for i := 0; i < count; i++ { 23 cid := int64(i) 24 player := &Player{ 25 cid: cid, 26 name: strconv.FormatInt(cid, 10), 27 } 28 players = append(players, player) 29 } 30 b.Run("slc add", func(b *testing.B) { 31 b.ReportAllocs() 32 for _, player := range players { 33 slc = append(slc, player) 34 } 35 }) 36 b.Run("map add", func(b *testing.B) { 37 b.ReportAllocs() 38 for _, player := range players { 39 mp[player.cid] = player 40 } 41 }) 42 b.Run("set add", func(b *testing.B) { 43 b.ReportAllocs() 44 for _, player := range players { 45 _ = set.Add(player) 46 } 47 }) 48 delIds := make([]int64, 0, count) 49 for i := 0; i < count; i++ { 50 m := rand.Intn(len(players)) 51 delIds = append(delIds, players[m].cid) 52 } 53 rangFn := func(player *Player) {} 54 b.Run("slc range", func(b *testing.B) { 55 b.ReportAllocs() 56 for _, player := range slc { 57 rangFn(player) 58 } 59 }) 60 b.Run("map range", func(b *testing.B) { 61 b.ReportAllocs() 62 for _, player := range mp { 63 rangFn(player) 64 } 65 }) 66 b.Run("set range", func(b *testing.B) { 67 b.ReportAllocs() 68 set.Iter(rangFn) 69 }) 70 b.Run("slc del", func(b *testing.B) { 71 b.ReportAllocs() 72 for _, id := range delIds { 73 for i, player := range slc { 74 if player.cid == id { 75 slc = append(slc[:i], slc[i+1:]...) 76 break 77 } 78 } 79 } 80 }) 81 b.Run("map del", func(b *testing.B) { 82 b.ReportAllocs() 83 for _, id := range delIds { 84 delete(mp, id) 85 } 86 }) 87 b.Run("set del", func(b *testing.B) { 88 b.ReportAllocs() 89 for _, id := range delIds { 90 set.Del(id) 91 } 92 }) 93 }