github.com/GitbookIO/syncgroup@v0.0.0-20200915204659-4f0b2961ab10/quickhash/strhash_test.go (about)

     1  package quickhash
     2  
     3  import (
     4  	"unsafe"
     5  
     6  	"testing"
     7  )
     8  
     9  func TestStrHash(t *testing.T) {
    10  	x0 := "abc"
    11  	b := "b"
    12  	b2 := "a" + b + "c"
    13  	x1 := StrHash(x0)
    14  	x2 := StrHash(x0)
    15  	x3 := StrHash(b2)
    16  	y0 := "def"
    17  	y1 := StrHash(y0)
    18  	y2 := StrHash(y0)
    19  
    20  	if x1 != x2 || x2 != x3 {
    21  		t.Errorf("x: should all be equal: %d - %d - %d", x1, x2, x3)
    22  	}
    23  	if !(unsafe.Pointer(&x0) != unsafe.Pointer(&b2) && x1 == x3) {
    24  		t.Errorf("Hash should work on string value not pointer")
    25  	}
    26  	if y1 == x1 {
    27  		t.Errorf("Different input strings should nearly 'always' have different hashes: %d - %d", x1, y1)
    28  	}
    29  	if y1 != y2 {
    30  		t.Errorf("y: should all be equal: %d - %d", y1, y2)
    31  	}
    32  }
    33  
    34  func TestStrVSByte(t *testing.T) {
    35  	keys := []string{
    36  		"a",
    37  		"abc",
    38  		"123456",
    39  		"blablabla",
    40  	}
    41  
    42  	for _, k := range keys {
    43  		h1 := StrHash(k)
    44  		h2 := ByteHash([]byte(k))
    45  		if h1 != h2 {
    46  			t.Errorf("Expected str & byte hashes to be equal got: %d vs %d", h1, h2)
    47  		}
    48  	}
    49  }
    50  
    51  func BenchmarkStrHash(b *testing.B) {
    52  	x0 := "abcdefghijklmnopqrstuvwxyz"
    53  	for n := 0; n < b.N; n++ {
    54  		StrHash(x0)
    55  	}
    56  }
    57  
    58  func BenchmarkAesHash(b *testing.B) {
    59  	x0 := "abcdefghijklmnopqrstuvwxyz"
    60  	for n := 0; n < b.N; n++ {
    61  		StrHash(x0)
    62  	}
    63  }
    64  
    65  func BenchmarkFnvHash(b *testing.B) {
    66  	x0 := "abcdefghijklmnopqrstuvwxyz"
    67  	for n := 0; n < b.N; n++ {
    68  		FnvStr(x0)
    69  	}
    70  }
    71  
    72  func BenchmarkMapHash(b *testing.B) {
    73  	key := "abcdefghijklmnopqrstuvwxyz"
    74  	t := map[string]int64{
    75  		key: 99,
    76  	}
    77  	for n := 0; n < b.N; n++ {
    78  		_ = t[key]
    79  	}
    80  }
    81  
    82  func FnvStr(str string) uint64 {
    83  	return Fnv64a([]byte(str))
    84  }