From 92a2290544ed4cf4a83871f5b77e6dc73e801611 Mon Sep 17 00:00:00 2001 From: Francisco Date: Fri, 2 Oct 2026 10:46:51 -0500 Subject: [PATCH 1/2] Add a benchmark for unions of interleaved containers One bitmap has containers at even keys and the other one at odd keys, so every container of one side is missing from the other side. --- benchmarks/benches/lib.rs | 63 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 62 insertions(+), 1 deletion(-) diff --git a/benchmarks/benches/lib.rs b/benchmarks/benches/lib.rs index 9856ff38..166d2b5d 100644 --- a/benchmarks/benches/lib.rs +++ b/benchmarks/benches/lib.rs @@ -581,6 +581,66 @@ fn successive_or(c: &mut Criterion) { group.finish(); } +fn interleaved_containers(c: &mut Criterion) { + let mut group = c.benchmark_group("interleaved_containers"); + group.sample_size(10); + + // One bitmap has containers at even keys and the other one at odd keys, + // so that none of the containers of one side exists on the other side. + for size in [8192u32, 16384, 32768] { + let even: RoaringBitmap = (0..size).map(|key| key << 17).collect(); + let odd: RoaringBitmap = (0..size).map(|key| (key << 17) | (1 << 16)).collect(); + + group.bench_function(BenchmarkId::new("or_assign_own", size), |b| { + b.iter_batched( + || (even.clone(), odd.clone()), + |(mut a, b)| { + a |= b; + a + }, + BatchSize::LargeInput, + ); + }); + + group.bench_function(BenchmarkId::new("or_assign_ref", size), |b| { + b.iter_batched( + || even.clone(), + |mut a| { + a |= &odd; + a + }, + BatchSize::LargeInput, + ); + }); + + group.bench_function(BenchmarkId::new("multi_or_own", size), |b| { + b.iter_batched( + || [even.clone(), odd.clone()], + |bitmaps| bitmaps.union(), + BatchSize::LargeInput, + ); + }); + + group.bench_function(BenchmarkId::new("multi_or_ref", size), |b| { + b.iter(|| [&even, &odd].union()); + }); + + group.bench_function(BenchmarkId::new("multi_xor_own", size), |b| { + b.iter_batched( + || [even.clone(), odd.clone()], + |bitmaps| bitmaps.symmetric_difference(), + BatchSize::LargeInput, + ); + }); + + group.bench_function(BenchmarkId::new("multi_xor_ref", size), |b| { + b.iter(|| [&even, &odd].symmetric_difference()); + }); + } + + group.finish(); +} + // LEGACY BENCHMARKS // ================= @@ -765,6 +825,7 @@ criterion_group!( serialization, deserialization, successive_and, - successive_or + successive_or, + interleaved_containers ); criterion_main!(benches); From e460b1790c87ea050be00e5f8dcca1169b56f650 Mon Sep 17 00:00:00 2001 From: Francisco Date: Fri, 2 Oct 2026 10:46:51 -0500 Subject: [PATCH 2/2] Avoid quadratic container insertions in unions BitOrAssign and the MultiOps union and symmetric difference insert each right-hand container missing on the left with Vec::insert. Every insert shifts the containers after it, so when the right side brings many containers interleaved with the left ones, the operation is quadratic in the number of containers. Containers are still inserted directly when that shifts fewer than 64 containers, and for the first eight insertions that shift more. The other ones are deferred and merged into the vector in a single pass, which only moves the containers that follow the first deferred one. --- roaring/src/bitmap/multiops.rs | 10 ++- roaring/src/bitmap/ops.rs | 9 +- roaring/src/bitmap/util.rs | 87 +++++++++++++++++++- roaring/tests/symmetric_difference_with.rs | 77 ++++++++++++++++- roaring/tests/union_with.rs | 96 +++++++++++++++++++++- 5 files changed, 271 insertions(+), 8 deletions(-) diff --git a/roaring/src/bitmap/multiops.rs b/roaring/src/bitmap/multiops.rs index 4ba588aa..98a588a3 100644 --- a/roaring/src/bitmap/multiops.rs +++ b/roaring/src/bitmap/multiops.rs @@ -9,7 +9,7 @@ use alloc::borrow::Cow; use crate::{MultiOps, RoaringBitmap}; -use super::{container::Container, store::Store}; +use super::{container::Container, store::Store, util::SortedInserts}; #[cfg(not(feature = "std"))] use alloc::vec::Vec; @@ -274,9 +274,10 @@ fn merge_container_owned( rhs: Vec, op: impl Fn(&mut Store, Store), ) { + let mut inserts = SortedInserts::new(); for mut rhs in rhs { match lhs.binary_search_by_key(&rhs.key, |c| c.key) { - Err(loc) => lhs.insert(loc, rhs), + Err(loc) => inserts.insert(lhs, loc, rhs), Ok(loc) => { let lhs = &mut lhs[loc]; match (&lhs.store, &rhs.store) { @@ -288,6 +289,7 @@ fn merge_container_owned( } } } + inserts.finish(lhs); } #[inline] @@ -390,11 +392,12 @@ fn merge_container_ref<'a>( rhs: &'a [Container], op: impl Fn(&mut Store, &Store), ) { + let mut inserts = SortedInserts::new(); for rhs in rhs { match containers.binary_search_by_key(&rhs.key, |c| c.key) { Err(loc) => { // A container not currently in containers. Borrow it. - containers.insert(loc, Cow::Borrowed(rhs)) + inserts.insert(containers, loc, Cow::Borrowed(rhs)) } Ok(loc) => { // A container that is in containers. Operate on it. @@ -431,6 +434,7 @@ fn merge_container_ref<'a>( } } } + inserts.finish(containers); } #[inline] diff --git a/roaring/src/bitmap/ops.rs b/roaring/src/bitmap/ops.rs index 4337dbdb..d1baafc1 100644 --- a/roaring/src/bitmap/ops.rs +++ b/roaring/src/bitmap/ops.rs @@ -2,6 +2,7 @@ use core::mem; use core::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Sub, SubAssign}; use crate::bitmap::container::Container; +use crate::bitmap::util::SortedInserts; use crate::bitmap::Pairs; use crate::RoaringBitmap; @@ -161,26 +162,30 @@ impl BitOrAssign for RoaringBitmap { mem::swap(self, &mut rhs); } + let mut inserts = SortedInserts::new(); for container in rhs.containers { let key = container.key; match self.containers.binary_search_by_key(&key, |c| c.key) { - Err(loc) => self.containers.insert(loc, container), + Err(loc) => inserts.insert(&mut self.containers, loc, container), Ok(loc) => BitOrAssign::bitor_assign(&mut self.containers[loc], container), } } + inserts.finish(&mut self.containers); } } impl BitOrAssign<&RoaringBitmap> for RoaringBitmap { /// An `union` between two sets. fn bitor_assign(&mut self, rhs: &RoaringBitmap) { + let mut inserts = SortedInserts::new(); for container in &rhs.containers { let key = container.key; match self.containers.binary_search_by_key(&key, |c| c.key) { - Err(loc) => self.containers.insert(loc, container.clone()), + Err(loc) => inserts.insert(&mut self.containers, loc, container.clone()), Ok(loc) => BitOrAssign::bitor_assign(&mut self.containers[loc], container), } } + inserts.finish(&mut self.containers); } } diff --git a/roaring/src/bitmap/util.rs b/roaring/src/bitmap/util.rs index 80a4896e..210c613a 100644 --- a/roaring/src/bitmap/util.rs +++ b/roaring/src/bitmap/util.rs @@ -1,5 +1,8 @@ use core::ops::{Bound, RangeBounds, RangeInclusive}; +#[cfg(not(feature = "std"))] +use alloc::vec::Vec; + /// Returns the container key and the index /// in this container for a given integer. #[inline] @@ -61,11 +64,66 @@ where } } +// Thresholds of `SortedInserts`, picked from benchmarks. +const FEW_INSERTS: usize = 8; +const SHORT_SHIFT: usize = 64; + +/// Inserts values into a sorted `Vec` at the positions given by failed binary searches. +/// +/// Every insertion shifts the values after it, which is quadratic when many values are +/// interleaved with the existing ones. So a value is only inserted directly when that is +/// cheap: when it shifts fewer than `SHORT_SHIFT` values, or for the first `FEW_INSERTS` +/// values that shift more. The other ones are deferred and merged into the vector by +/// `finish` in a single pass. +pub struct SortedInserts { + long_inserts: usize, + deferred: Vec<(usize, T)>, +} + +impl SortedInserts { + pub fn new() -> Self { + SortedInserts { long_inserts: 0, deferred: Vec::new() } + } + + /// Inserts `value` at `index` in `vec`, or defers it until `finish` is called. + /// `index` must come from a failed binary search in `vec`, and values must be + /// given in ascending order. + pub fn insert(&mut self, vec: &mut Vec, index: usize, value: T) { + let short = vec.len() - index < SHORT_SHIFT; + if short || self.long_inserts < FEW_INSERTS { + // The deferred indexes stay valid: the values deferred so far belong at or + // before `index`, so before `value`. + vec.insert(index, value); + self.long_inserts += usize::from(!short); + } else { + self.deferred.push((index, value)); + } + } + + /// Merges the deferred values into `vec`, moving the values that follow the first + /// deferred index once. + pub fn finish(self, vec: &mut Vec) { + let Some(&(start, _)) = self.deferred.first() else { return }; + vec.reserve(self.deferred.len()); + let mut tail = vec.split_off(start).into_iter(); + let mut prev = start; + for (index, value) in self.deferred { + vec.extend(tail.by_ref().take(index - prev)); + vec.push(value); + prev = index; + } + vec.extend(tail); + } +} + #[cfg(test)] mod test { - use super::{convert_range_to_inclusive, join, split, ConvertRangeError}; + use super::{convert_range_to_inclusive, join, split, ConvertRangeError, SortedInserts}; use core::ops::Bound; + #[cfg(not(feature = "std"))] + use alloc::vec::Vec; + #[test] fn test_split_u32() { assert_eq!((0x0000u16, 0x0000u16), split(0x0000_0000u32)); @@ -119,4 +177,31 @@ mod test { convert_range_to_inclusive((Bound::Excluded(0), Bound::Included(0))) ); } + + #[test] + fn test_sorted_inserts() { + fn check(mut vec: Vec, values: Vec) { + let mut expected = [vec.as_slice(), values.as_slice()].concat(); + expected.sort_unstable(); + + let mut inserts = SortedInserts::new(); + for value in values { + let index = vec.binary_search(&value).unwrap_err(); + inserts.insert(&mut vec, index, value); + } + inserts.finish(&mut vec); + assert_eq!(vec, expected); + } + + let even: Vec = (0..1000).map(|i| 2 * i).collect(); + let odd: Vec = (0..1000).map(|i| 2 * i + 1).collect(); + check(even.clone(), odd.clone()); + check(odd.clone(), even.clone()); + check(even.clone(), (0..5).map(|i| 400 * i + 1).collect()); + check(even.clone(), (2000..3000).collect()); + check(even[500..600].to_vec(), odd[..100].iter().chain(&odd[900..]).copied().collect()); + check(even[..10].to_vec(), odd[..100].to_vec()); + check(Vec::new(), odd.clone()); + check(even, Vec::new()); + } } diff --git a/roaring/tests/symmetric_difference_with.rs b/roaring/tests/symmetric_difference_with.rs index d9c2bf5a..d33a5470 100644 --- a/roaring/tests/symmetric_difference_with.rs +++ b/roaring/tests/symmetric_difference_with.rs @@ -1,5 +1,9 @@ extern crate roaring; -use roaring::RoaringBitmap; +use std::collections::BTreeSet; + +use proptest::collection::vec; +use proptest::prelude::*; +use roaring::{MultiOps, RoaringBitmap}; #[test] fn array() { @@ -122,3 +126,74 @@ fn bitmaps() { assert_eq!(bitmap1, bitmap3); } + +#[test] +fn interleaved_containers() { + // One side has containers at even keys and the other one at odd keys. + let even = (0..4096).map(|key| key << 17).collect::(); + let odd = (0..4096).map(|key| (key << 17) | (1 << 16)).collect::(); + let expected = (0..8192).map(|key| key << 16).collect::(); + + let mut bitmap = even.clone(); + bitmap ^= &odd; + assert_eq!(bitmap, expected); + + let mut bitmap = odd.clone(); + bitmap ^= even.clone(); + assert_eq!(bitmap, expected); + + assert_eq!([&even, &odd].symmetric_difference(), expected); + assert_eq!([odd, even].symmetric_difference(), expected); +} + +/// A bitmap made of ranges of up to 64 values spread over up to 512 containers, +/// along with the set of its values. +fn bitmap_and_set() -> impl Strategy)> { + vec((0u32..512, any::(), 0u32..64), 0..256).prop_map(|ranges| { + let mut bitmap = RoaringBitmap::new(); + let mut set = BTreeSet::new(); + for (key, low, len) in ranges { + let start = (key << 16) | u32::from(low); + let end = (start + len).min(start | 0xFFFF); + bitmap.insert_range(start..=end); + set.extend(start..=end); + } + (bitmap, set) + }) +} + +proptest! { + #[test] + fn symmetric_difference_matches_btreeset( + (a, set_a) in bitmap_and_set(), + (b, set_b) in bitmap_and_set(), + (c, set_c) in bitmap_and_set(), + ) { + let expected = &set_a ^ &set_b; + + let mut assign_ref = a.clone(); + assign_ref ^= &b; + let mut assign_own = a.clone(); + assign_own ^= b.clone(); + + for bitmap in [ + assign_ref, + assign_own, + &a ^ &b, + &a ^ b.clone(), + a.clone() ^ &b, + a.clone() ^ b.clone(), + [&a, &b].symmetric_difference(), + [a.clone(), b.clone()].symmetric_difference(), + ] { + prop_assert_eq!(bitmap.len(), expected.len() as u64); + prop_assert!(bitmap.iter().eq(expected.iter().copied())); + } + + let expected = &expected ^ &set_c; + for bitmap in [[&a, &b, &c].symmetric_difference(), [a, b, c].symmetric_difference()] { + prop_assert_eq!(bitmap.len(), expected.len() as u64); + prop_assert!(bitmap.iter().eq(expected.iter().copied())); + } + } +} diff --git a/roaring/tests/union_with.rs b/roaring/tests/union_with.rs index 765b8295..8723e435 100644 --- a/roaring/tests/union_with.rs +++ b/roaring/tests/union_with.rs @@ -1,5 +1,9 @@ extern crate roaring; -use roaring::RoaringBitmap; +use std::collections::BTreeSet; + +use proptest::collection::vec; +use proptest::prelude::*; +use roaring::{MultiOps, RoaringBitmap}; #[test] fn array_to_array() { @@ -97,3 +101,93 @@ fn bitmaps() { assert_eq!(bitmap1, bitmap3); } + +#[test] +fn interleaved_containers() { + // One side has containers at even keys and the other one at odd keys. + let even = (0..4096).map(|key| key << 17).collect::(); + let odd = (0..4096).map(|key| (key << 17) | (1 << 16)).collect::(); + let expected = (0..8192).map(|key| key << 16).collect::(); + + let mut bitmap = even.clone(); + bitmap |= &odd; + assert_eq!(bitmap, expected); + + let mut bitmap = odd.clone(); + bitmap |= even.clone(); + assert_eq!(bitmap, expected); + + assert_eq!([&even, &odd].union(), expected); + assert_eq!([odd, even].union(), expected); +} + +#[test] +fn containers_before_and_after() { + let middle = (100..200).map(|key| key << 16).collect::(); + let outside = (0..50).chain(250..300).map(|key| key << 16).collect::(); + let expected = + (0..50).chain(100..200).chain(250..300).map(|key| key << 16).collect::(); + + let mut bitmap = middle.clone(); + bitmap |= &outside; + assert_eq!(bitmap, expected); + + let mut bitmap = middle.clone(); + bitmap |= outside.clone(); + assert_eq!(bitmap, expected); + + assert_eq!([&middle, &outside].union(), expected); + assert_eq!([middle, outside].union(), expected); +} + +/// A bitmap made of ranges of up to 64 values spread over up to 512 containers, +/// along with the set of its values. +fn bitmap_and_set() -> impl Strategy)> { + vec((0u32..512, any::(), 0u32..64), 0..256).prop_map(|ranges| { + let mut bitmap = RoaringBitmap::new(); + let mut set = BTreeSet::new(); + for (key, low, len) in ranges { + let start = (key << 16) | u32::from(low); + let end = (start + len).min(start | 0xFFFF); + bitmap.insert_range(start..=end); + set.extend(start..=end); + } + (bitmap, set) + }) +} + +proptest! { + #[test] + fn union_matches_btreeset( + (a, set_a) in bitmap_and_set(), + (b, set_b) in bitmap_and_set(), + (c, set_c) in bitmap_and_set(), + ) { + let expected = &set_a | &set_b; + + let mut assign_ref = a.clone(); + assign_ref |= &b; + let mut assign_own = a.clone(); + assign_own |= b.clone(); + + for bitmap in [ + assign_ref, + assign_own, + &a | &b, + &a | b.clone(), + a.clone() | &b, + a.clone() | b.clone(), + [&a, &b].union(), + [a.clone(), b.clone()].union(), + ] { + prop_assert_eq!(bitmap.len(), expected.len() as u64); + prop_assert!(bitmap.iter().eq(expected.iter().copied())); + } + + let expected = &expected | &set_c; + for bitmap in [[&a, &b, &c].union(), [a, b, c].union()] { + prop_assert_eq!(bitmap.len(), expected.len() as u64); + prop_assert!(bitmap.iter().eq(expected.iter().copied())); + } + } +}