Skip to content

Commit

Permalink
reduce allocations during encode/decode
Browse files Browse the repository at this point in the history
  • Loading branch information
paulwe committed Jun 10, 2023
1 parent f90a0b9 commit 1534289
Showing 1 changed file with 8 additions and 6 deletions.
14 changes: 8 additions & 6 deletions cuckoofilter.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,15 +129,13 @@ const bytesPerBucket = bucketSize * fingerprintSizeBits / 8

// Encode returns a byte slice representing a Cuckoofilter.
func (cf *Filter) Encode() []byte {
res := new(bytes.Buffer)
res.Grow(len(cf.buckets) * bytesPerBucket)

buf := make([]byte, 0, len(cf.buckets)*bytesPerBucket)
for _, b := range cf.buckets {
for _, fp := range b {
binary.Write(res, binary.LittleEndian, fp)
buf = binary.LittleEndian.AppendUint16(buf, uint16(fp))
}
}
return res.Bytes()
return buf
}

// Decode returns a Cuckoofilter from a byte slice created using Encode.
Expand All @@ -156,9 +154,13 @@ func Decode(data []byte) (*Filter, error) {
buckets := make([]bucket, numBuckets)
reader := bytes.NewReader(data)

buf := make([]byte, 2)
for i, b := range buckets {
for j := range b {
binary.Read(reader, binary.LittleEndian, &buckets[i][j])
if _, err := reader.Read(buf); err != nil {
return nil, err
}
buckets[i][j] = fingerprint(binary.LittleEndian.Uint16(buf))
if buckets[i][j] != nullFp {
count++
}
Expand Down

0 comments on commit 1534289

Please sign in to comment.