From 910d83ae7cbdc48e18c5a2421ac26169ddfe2d12 Mon Sep 17 00:00:00 2001 From: imalasong Date: Fri, 3 May 2024 13:05:37 +0800 Subject: [PATCH] optimize: ContainesHash method adopts fast failure --- v2/bloomfilter.go | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/v2/bloomfilter.go b/v2/bloomfilter.go index e78f3a4..e932ff8 100644 --- a/v2/bloomfilter.go +++ b/v2/bloomfilter.go @@ -77,16 +77,18 @@ func (f *Filter) AddHash(hash uint64) { func (f *Filter) ContainsHash(hash uint64) bool { f.lock.RLock() defer f.lock.RUnlock() - var ( - i uint64 - r = uint64(1) - ) - for n := 0; n < len(f.keys) && r != 0; n++ { + + for n := 0; n < len(f.keys); n++ { hash = ((hash << rotation) | (hash >> (64 - rotation))) ^ f.keys[n] - i = hash % f.m - r &= (f.bits[i>>6] >> uint(i&0x3f)) & 1 + i := hash % f.m + + b := f.bits[i>>6] & (1 << uint(i&0x3f)) + if b == 0 { + // Any bit that does not exist is not non-existent + return false + } } - return r != 0 + return true } // Contains tests if f contains v