Skip to content

Commit

Permalink
performance: improved bitmap's minimum and maximum methods
Browse files Browse the repository at this point in the history
  • Loading branch information
aliszka committed Dec 17, 2024
1 parent a00d2da commit 398775d
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 15 deletions.
39 changes: 24 additions & 15 deletions container.go
Original file line number Diff line number Diff line change
Expand Up @@ -636,32 +636,41 @@ func (b bitmap) isFull() bool {
}

func (b bitmap) minimum() uint16 {
N := getCardinality(b)
if N == 0 {
if N := getCardinality(b); N == 0 {
return 0
}
for i, x := range b[startIdx:] {
lz := bits.LeadingZeros16(x)
if lz == 16 {
continue

b64 := uint16To64SliceUnsafe(b[startIdx:])
for i := 0; i < len(b64); i++ {
if b64[i] != 0 {
for j := 0; j < 4; j++ {
idx := i*4 + j
if lz := bits.LeadingZeros16(b[idx+int(startIdx)]); lz != 16 {
return uint16(16*idx + lz)
}
}
break
}
return uint16(16*i + lz)
}
panic("We shouldn't reach here")
}

func (b bitmap) maximum() uint16 {
N := getCardinality(b)
if N == 0 {
if N := getCardinality(b); N == 0 {
return 0
}
for i := len(b) - 1; i >= int(startIdx); i-- {
x := b[i]
tz := bits.TrailingZeros16(x)
if tz == 16 {
continue

b64 := uint16To64SliceUnsafe(b[startIdx:])
for i := len(b64) - 1; i >= 0; i-- {
if b64[i] != 0 {
for j := 3; j >= 0; j-- {
idx := i*4 + j
if tz := bits.TrailingZeros16(b[idx+int(startIdx)]); tz != 16 {
return uint16(16*idx + 15 - tz)
}
}
break
}
return uint16(16*(i-int(startIdx)) + 15 - tz)
}
panic("We shouldn't reach here")
}
Expand Down
40 changes: 40 additions & 0 deletions container_opt_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package sroar

import (
"fmt"
"testing"

"github.com/stretchr/testify/require"
)

func TestContainerExtremes(t *testing.T) {
bitmapYs := []int{
0, 1, 15, 16, 17, 1022, 1023, 1024, 1025,
maxCardinality/2 - 1, maxCardinality / 2, maxCardinality/2 + 1,
maxCardinality - 3, maxCardinality - 2, maxCardinality - 1,
}

t.Run("bitmap maximum", func(t *testing.T) {
b := bitmap(make([]uint16, maxContainerSize))

for i := 0; i < len(bitmapYs); i++ {
y := uint16(bitmapYs[i])
t.Run(fmt.Sprint(y), func(t *testing.T) {
b.add(y)
require.Equal(t, y, b.maximum())
})
}
})

t.Run("bitmap minimum", func(t *testing.T) {
b := bitmap(make([]uint16, maxContainerSize))

for i := len(bitmapYs) - 1; i >= 0; i-- {
y := uint16(bitmapYs[i])
t.Run(fmt.Sprint(y), func(t *testing.T) {
b.add(y)
require.Equal(t, y, b.minimum())
})
}
})
}

0 comments on commit 398775d

Please sign in to comment.