Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions sql/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package sql
import (
"fmt"
"runtime"
"sync"

"github.com/cespare/xxhash/v2"

Expand All @@ -25,7 +26,9 @@ import (

// HashOf returns a hash of the given value to be used as key in a cache.
func HashOf(v Row) (uint64, error) {
hash := xxhash.New()
hash := digestPool.Get().(*xxhash.Digest)
hash.Reset()
defer digestPool.Put(hash)
for i, x := range v {
if i > 0 {
// separate each value in the row with a nil byte
Expand All @@ -38,13 +41,19 @@ func HashOf(v Row) (uint64, error) {
// TODO: we don't have the type info necessary to appropriately encode the value of a string with a non-standard
// collation, which means that two strings that differ only in their collations will hash to the same value.
// See rowexec/grouping_key()
if _, err := hash.Write([]byte(fmt.Sprintf("%v,", x))); err != nil {
if _, err := fmt.Fprintf(hash, "%v,", x); err != nil {
return 0, err
}
}
return hash.Sum64(), nil
}

var digestPool = sync.Pool{
New: func() any {
return xxhash.New()
},
}

// ErrKeyNotFound is returned when the key could not be found in the cache.
var ErrKeyNotFound = fmt.Errorf("memory: key not found in cache")

Expand Down
30 changes: 30 additions & 0 deletions sql/cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,3 +177,33 @@ func TestRowsCache(t *testing.T) {
require.True(freed)
})
}

func BenchmarkHashOf(b *testing.B) {
row := NewRow(1, "1")
b.ResetTimer()
for i := 0; i < b.N; i++ {
sum, err := HashOf(row)
if err != nil {
b.Fatal(err)
}
if sum != 11268758894040352165 {
b.Fatalf("got %v", sum)
}
}
}

func BenchmarkParallelHashOf(b *testing.B) {
row := NewRow(1, "1")
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
sum, err := HashOf(row)
if err != nil {
b.Fatal(err)
}
if sum != 11268758894040352165 {
b.Fatalf("got %v", sum)
}
}
})
}