1
0
mirror of https://github.com/charlienet/go-mixed.git synced 2025-07-18 08:32:40 +08:00
This commit is contained in:
2022-03-28 17:35:58 +08:00
parent abeabeeb61
commit a5fb792dcf
4 changed files with 158 additions and 12 deletions

View File

@ -5,7 +5,9 @@ import (
"runtime"
"testing"
"github.com/charlienet/go-mixed/bytesconv"
"github.com/charlienet/go-mixed/collections/generics"
"github.com/charlienet/go-mixed/hash"
)
func TestConcurrentMap(t *testing.T) {
@ -81,3 +83,86 @@ func BenchmarkRWLockMap(b *testing.B) {
}
})
}
func BenchmarkGetIndex(b *testing.B) {
b.Run("字符串-Sprintf", func(b *testing.B) {
v := "abc"
for i := 0; i < b.N; i++ {
bytes := []byte(fmt.Sprintf("%v", v))
hash.XXHashUint64(bytes)
}
})
b.Run("字符串", func(b *testing.B) {
v := "abc"
for i := 0; i < b.N; i++ {
getTag(v)
}
})
b.Run("数字", func(b *testing.B) {
v := 124
for i := 0; i < b.N; i++ {
getTag(v)
}
})
}
func getTag[T comparable](v T) uint64 {
var vv any = v
switch vv.(type) {
case string:
return getStringIndex([]byte(vv.(string)))
case int8:
return uint64(vv.(int8))
case uint8:
return uint64(vv.(uint8))
case int:
return uint64(vv.(int))
case int32:
return uint64(vv.(int32))
case uint32:
return uint64(vv.(uint32))
case int64:
return uint64(vv.(int64))
case uint64:
return vv.(uint64)
default:
return getStringIndex([]byte(fmt.Sprintf("%v", v)))
}
}
func getStringIndex(v []byte) uint64 {
if len(v) > 4 {
v = v[:4]
}
// return hash.XXHashUint64(v)
i, _ := bytesconv.BigEndian.BytesToUInt64(v)
return i
}
func TestFnv64(t *testing.T) {
t.Log(fnv64("a"))
t.Log(fnv64("b"))
t.Log(fnv64("c"))
t.Log(fnv64("d"))
t.Log(fnv64("e"))
}
const (
prime32 = uint64(16777619)
)
func fnv64(k string) uint64 {
var hash = uint64(2166136261)
l := len(k)
for i := 0; i < l; i++ {
hash *= prime32
hash ^= uint64(k[i])
}
return hash
}