You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "adriangb (via GitHub)" <gi...@apache.org> on 2025/11/20 00:07:57 UTC

[PR] add specialized InList implementations for common scalar types [datafusion]

adriangb opened a new pull request, #18832:
URL: https://github.com/apache/datafusion/pull/18832

   Closes #18824


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "Dandandan (via GitHub)" <gi...@apache.org>.
Dandandan commented on code in PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#discussion_r2553808933


##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,68 +211,127 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
-    null_count: usize,
-    values: HashSet<i32>,
-}
+// Macro to generate specialized StaticFilter implementations for primitive types
+macro_rules! primitive_static_filter {
+    ($Name:ident, $ArrowType:ty) => {
+        struct $Name {
+            null_count: usize,
+            values: HashSet<<$ArrowType as ArrowPrimitiveType>::Native>,
+        }
 
-impl Int32StaticFilter {
-    fn try_new(in_array: &ArrayRef) -> Result<Self> {
-        let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+        impl $Name {
+            fn try_new(in_array: &ArrayRef) -> Result<Self> {
+                let in_array = in_array
+                    .as_primitive_opt::<$ArrowType>()
+                    .ok_or_else(|| exec_datafusion_err!("Failed to downcast an array to a '{}' array", stringify!($ArrowType)))?;
 
-        let mut values = HashSet::with_capacity(in_array.len());
-        let null_count = in_array.null_count();
+                let mut values = HashSet::with_capacity(in_array.len());
+                let null_count = in_array.null_count();
+
+                for v in in_array.iter().flatten() {
+                    values.insert(v);
+                }
 
-        for v in in_array.iter().flatten() {
-            values.insert(v);
+                Ok(Self { null_count, values })
+            }
         }
 
-        Ok(Self { null_count, values })
-    }
-}
+        impl StaticFilter for $Name {
+            fn null_count(&self) -> usize {
+                self.null_count
+            }
 
-impl StaticFilter for Int32StaticFilter {
-    fn null_count(&self) -> usize {
-        self.null_count
-    }
+            fn contains(&self, v: &dyn Array, negated: bool) -> Result<BooleanArray> {
+                // Handle dictionary arrays by recursing on the values
+                downcast_dictionary_array! {
+                    v => {
+                        let values_contains = self.contains(v.values().as_ref(), negated)?;
+                        let result = take(&values_contains, v.keys(), None)?;
+                        return Ok(downcast_array(result.as_ref()))
+                    }
+                    _ => {}
+                }
 
-    fn contains(&self, v: &dyn Array, negated: bool) -> Result<BooleanArray> {
-        let v = v
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
-
-        let result = match (v.null_count() > 0, negated) {
-            (true, false) => {
-                // has nulls, not negated"
-                BooleanArray::from_iter(
-                    v.iter().map(|value| Some(self.values.contains(&value?))),
-                )
-            }
-            (true, true) => {
-                // has nulls, negated
-                BooleanArray::from_iter(
-                    v.iter().map(|value| Some(!self.values.contains(&value?))),
-                )
-            }
-            (false, false) => {
-                //no null, not negated
-                BooleanArray::from_iter(
-                    v.values().iter().map(|value| self.values.contains(value)),
-                )
-            }
-            (false, true) => {
-                // no null, negated
-                BooleanArray::from_iter(
-                    v.values().iter().map(|value| !self.values.contains(value)),
-                )
+                let v = v
+                    .as_primitive_opt::<$ArrowType>()
+                    .ok_or_else(|| exec_datafusion_err!("Failed to downcast an array to a '{}' array", stringify!($ArrowType)))?;
+
+                let haystack_has_nulls = self.null_count > 0;
+
+                let result = match (v.null_count() > 0, haystack_has_nulls, negated) {
+                    (true, _, false) | (false, true, false) => {
+                        // Either needle or haystack has nulls, not negated
+                        BooleanArray::from_iter(v.iter().map(|value| {
+                            match value {
+                                // SQL three-valued logic: null IN (...) is always null
+                                None => None,
+                                Some(v) => {
+                                    if self.values.contains(&v) {
+                                        Some(true)
+                                    } else if haystack_has_nulls {
+                                        // value not in set, but set has nulls -> null
+                                        None
+                                    } else {
+                                        Some(false)
+                                    }
+                                }
+                            }
+                        }))
+                    }
+                    (true, _, true) | (false, true, true) => {
+                        // Either needle or haystack has nulls, negated
+                        BooleanArray::from_iter(v.iter().map(|value| {
+                            match value {
+                                // SQL three-valued logic: null NOT IN (...) is always null
+                                None => None,
+                                Some(v) => {
+                                    if self.values.contains(&v) {
+                                        Some(false)
+                                    } else if haystack_has_nulls {
+                                        // value not in set, but set has nulls -> null
+                                        None
+                                    } else {
+                                        Some(true)
+                                    }
+                                }
+                            }
+                        }))
+                    }
+                    (false, false, false) => {
+                        // no nulls anywhere, not negated
+                        let values = v.values();
+                        let mut builder = BooleanBufferBuilder::new(values.len());
+                        for value in values.iter() {
+                            builder.append(self.values.contains(value));

Review Comment:
   This unfortunately is slower than `collect_bool`. I see there is some good discussion on better APIs on https://github.com/apache/arrow-rs/issues/8561



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3637956674

   > > @Dandandan is already on the list https://github.com/alamb/datafusion-benchmarking/blob/4fb120785fa66ecbf40a45d8a5d0d5f4be17266a/scripts/scrape_comments.py#L41
   > > I can add @geoffreyclaude if he would like
   > 
   > @alamb yes please :) Especially for when/if I follow through with the additional perf improvements.
   
   @geoffreyclaude  -- done in https://github.com/alamb/datafusion-benchmarking/commit/e3833a38b60eab1775f50b23b58653a8ea5dfa39
   
   Note that all these scripts are open source and anyone is welcome to run them - I just need to be a little more stringent on the people I allow to use my VM.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3638292609

   @alamb c1a29a2 seems to have made [quite a positive impact](https://github.com/apache/datafusion/pull/18832#issuecomment-3638118348):
   
   ```
   group                                          main                                   specialize
   -----                                          ----                                   ----------
   in_list/Float32/list=8/nulls=20%               1.11     39.4±0.40µs        ? ?/sec    1.00     35.4±0.36µs
   in_list/Int32/list=3/nulls=20%                 2.13      8.8±0.28µs        ? ?/sec    1.00      4.1±0.01µs        ? ?/sec
   ```
   
   I'll re-run to confirm. But maybe it's a good time to re-review?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "alamb-ghbot (via GitHub)" <gi...@apache.org>.
alamb-ghbot commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3634541381

   🤖 Hi @alamb, thanks for the request (https://github.com/apache/datafusion/pull/18832#issuecomment-3634537320).
   
   [`scrape_comments.py`](https://github.com/alamb/datafusion-benchmarking/blob/main/scripts/scrape_comments.py) only supports whitelisted benchmarks.
   - Standard: clickbench_1, clickbench_extended, clickbench_partitioned, clickbench_pushdown, tpch, tpch10, tpch_mem, tpch_mem10
   - Criterion: aggregate_query_sql, aggregate_vectorized, case_when, in_list, sql_planner
   
   Please choose one or more of these with `run benchmark <name>` or `run benchmark <name1> <name2>...`


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on code in PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#discussion_r2549920745


##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,68 +206,122 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
-    null_count: usize,
-    values: HashSet<i32>,
-}
+// Macro to generate specialized StaticFilter implementations for primitive types
+macro_rules! primitive_static_filter {
+    ($Name:ident, $ArrowType:ty) => {
+        struct $Name {
+            null_count: usize,
+            values: HashSet<<$ArrowType as ArrowPrimitiveType>::Native>,
+        }
 
-impl Int32StaticFilter {
-    fn try_new(in_array: &ArrayRef) -> Result<Self> {
-        let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+        impl $Name {
+            fn try_new(in_array: &ArrayRef) -> Result<Self> {
+                let in_array = in_array
+                    .as_primitive_opt::<$ArrowType>()
+                    .ok_or_else(|| exec_datafusion_err!(format!("Failed to downcast an array to a '{}' array", stringify!($ArrowType))))?;
 
-        let mut values = HashSet::with_capacity(in_array.len());
-        let null_count = in_array.null_count();
+                let mut values = HashSet::with_capacity(in_array.len());
+                let null_count = in_array.null_count();
+
+                for v in in_array.iter().flatten() {
+                    values.insert(v);
+                }
 
-        for v in in_array.iter().flatten() {
-            values.insert(v);
+                Ok(Self { null_count, values })
+            }
         }
 
-        Ok(Self { null_count, values })
-    }
-}
+        impl StaticFilter for $Name {
+            fn null_count(&self) -> usize {
+                self.null_count
+            }
 
-impl StaticFilter for Int32StaticFilter {
-    fn null_count(&self) -> usize {
-        self.null_count
-    }
+            fn contains(&self, v: &dyn Array, negated: bool) -> Result<BooleanArray> {
+                // Handle dictionary arrays by recursing on the values
+                downcast_dictionary_array! {
+                    v => {
+                        let values_contains = self.contains(v.values().as_ref(), negated)?;
+                        let result = take(&values_contains, v.keys(), None)?;
+                        return Ok(downcast_array(result.as_ref()))
+                    }
+                    _ => {}
+                }
 
-    fn contains(&self, v: &dyn Array, negated: bool) -> Result<BooleanArray> {
-        let v = v
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
-
-        let result = match (v.null_count() > 0, negated) {
-            (true, false) => {
-                // has nulls, not negated"
-                BooleanArray::from_iter(
-                    v.iter().map(|value| Some(self.values.contains(&value?))),
-                )
-            }
-            (true, true) => {
-                // has nulls, negated
-                BooleanArray::from_iter(
-                    v.iter().map(|value| Some(!self.values.contains(&value?))),
-                )
-            }
-            (false, false) => {
-                //no null, not negated
-                BooleanArray::from_iter(
-                    v.values().iter().map(|value| self.values.contains(value)),
-                )
-            }
-            (false, true) => {
-                // no null, negated
-                BooleanArray::from_iter(
-                    v.values().iter().map(|value| !self.values.contains(value)),
-                )
+                let v = v
+                    .as_primitive_opt::<$ArrowType>()
+                    .ok_or_else(|| exec_datafusion_err!(format!("Failed to downcast an array to a '{}' array", stringify!($ArrowType))))?;
+
+                let haystack_has_nulls = self.null_count > 0;
+
+                let result = match (v.null_count() > 0, haystack_has_nulls, negated) {
+                    (true, _, false) | (false, true, false) => {
+                        // Either needle or haystack has nulls, not negated
+                        BooleanArray::from_iter(v.iter().map(|value| {
+                            match value {
+                                // SQL three-valued logic: null IN (...) is always null
+                                None => None,
+                                Some(v) => {
+                                    if self.values.contains(&v) {
+                                        Some(true)
+                                    } else if haystack_has_nulls {
+                                        // value not in set, but set has nulls -> null
+                                        None
+                                    } else {
+                                        Some(false)
+                                    }
+                                }
+                            }
+                        }))
+                    }
+                    (true, _, true) | (false, true, true) => {
+                        // Either needle or haystack has nulls, negated
+                        BooleanArray::from_iter(v.iter().map(|value| {
+                            match value {
+                                // SQL three-valued logic: null NOT IN (...) is always null
+                                None => None,
+                                Some(v) => {
+                                    if self.values.contains(&v) {
+                                        Some(false)
+                                    } else if haystack_has_nulls {
+                                        // value not in set, but set has nulls -> null
+                                        None
+                                    } else {
+                                        Some(true)
+                                    }
+                                }
+                            }
+                        }))
+                    }
+                    (false, false, false) => {
+                        // no nulls anywhere, not negated
+                        BooleanArray::from_iter(

Review Comment:
   Thank you I know you or some other reviewer had pointed this out to me before. I am making a mental note to try to not forget again and keep an eye out for it. Thanks for you patience.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3567553330

   Yes. Slowdowns for i32 are concerning. I won’t merge this until it’s all speedups or neutral. I may also make a support PR to add more benchmarks for other types so we can make better comparisons.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#discussion_r2601382976


##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,65 +248,414 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
-    null_count: usize,
-    values: HashSet<i32>,
+/// Threshold for switching from sorted Vec (binary search) to HashSet
+/// For small lists, binary search has better cache locality and lower overhead
+/// Maximum list size for using sorted lookup (binary search).
+/// Lists with more elements use hash lookup instead.
+const SORTED_LOOKUP_MAX_LEN: usize = 8;
+
+/// Helper to build a BooleanArray result for IN list operations.
+/// Handles SQL three-valued logic for NULL values.
+///
+/// # Arguments
+/// * `len` - Number of elements in the needle array
+/// * `needle_nulls` - Optional validity buffer from the needle array
+/// * `haystack_has_nulls` - Whether the IN list contains NULL values
+/// * `negated` - Whether this is a NOT IN operation
+/// * `contains` - Closure that returns whether needle[i] is found in the haystack
+#[inline]
+fn build_in_list_result<C>(
+    len: usize,
+    needle_nulls: Option<&NullBuffer>,
+    haystack_has_nulls: bool,
+    negated: bool,
+    contains: C,
+) -> BooleanArray
+where
+    C: Fn(usize) -> bool,
+{
+    // Use collect_bool for all paths - it's vectorized and faster than element-by-element append.
+    // Match on (needle_has_nulls, haystack_has_nulls, negated) to specialize each case.
+    match (needle_nulls, haystack_has_nulls, negated) {
+        // Haystack has nulls: result is NULL when not found (might match the NULL)
+        // values_buf == nulls_buf, so compute once and clone
+        (Some(validity), true, false) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let buf = validity.inner() & &contains_buf;
+            BooleanArray::new(buf.clone(), Some(NullBuffer::new(buf)))
+        }
+        (None, true, false) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            BooleanArray::new(buf.clone(), Some(NullBuffer::new(buf)))
+        }
+        (Some(validity), true, true) => {
+            // Compute nulls_buf via SIMD AND, then derive values_buf via XOR.
+            // Uses identity: A & !B = A ^ (A & B) to get values from nulls.
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let nulls_buf = validity.inner() & &contains_buf;
+            let values_buf = validity.inner() ^ &nulls_buf; // valid & !contains
+            BooleanArray::new(values_buf, Some(NullBuffer::new(nulls_buf)))
+        }
+        (None, true, true) => {
+            // No needle nulls, but haystack has nulls
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = !&contains_buf;
+            BooleanArray::new(values_buf, Some(NullBuffer::new(contains_buf)))
+        }
+        // Only needle has nulls: nulls_buf is just validity (reuse it directly!)
+        (Some(validity), false, false) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = validity.inner() & &contains_buf;
+            BooleanArray::new(values_buf, Some(validity.clone()))
+        }
+        (Some(validity), false, true) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = validity.inner() & &(!&contains_buf);
+            BooleanArray::new(values_buf, Some(validity.clone()))
+        }
+        // No nulls anywhere: no validity buffer needed
+        (None, false, false) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            BooleanArray::new(buf, None)
+        }
+        (None, false, true) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| !contains(i));
+            BooleanArray::new(buf, None)
+        }
+    }
 }
 
-impl Int32StaticFilter {
-    fn try_new(in_array: &ArrayRef) -> Result<Self> {
-        let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+/// Sorted lookup using binary search. Best for small lists (< 8 elements).
+struct SortedLookup<T>(Vec<T>);
 
-        let mut values = HashSet::with_capacity(in_array.len());
-        let null_count = in_array.null_count();
+impl<T: Ord> SortedLookup<T> {
+    fn new(mut values: Vec<T>) -> Self {
+        values.sort_unstable();
+        values.dedup();
+        Self(values)
+    }
 
-        for v in in_array.iter().flatten() {
-            values.insert(v);
-        }
+    #[inline]
+    fn contains(&self, value: &T) -> bool {
+        self.0.binary_search(value).is_ok()

Review Comment:
   I wanted to do a bench of linear vs binary vs hash to see if thresholds come up



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "Dandandan (via GitHub)" <gi...@apache.org>.
Dandandan commented on code in PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#discussion_r2602052970


##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,65 +248,414 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
-    null_count: usize,
-    values: HashSet<i32>,
+/// Threshold for switching from sorted Vec (binary search) to HashSet
+/// For small lists, binary search has better cache locality and lower overhead
+/// Maximum list size for using sorted lookup (binary search).
+/// Lists with more elements use hash lookup instead.
+const SORTED_LOOKUP_MAX_LEN: usize = 8;
+
+/// Helper to build a BooleanArray result for IN list operations.
+/// Handles SQL three-valued logic for NULL values.
+///
+/// # Arguments
+/// * `len` - Number of elements in the needle array
+/// * `needle_nulls` - Optional validity buffer from the needle array
+/// * `haystack_has_nulls` - Whether the IN list contains NULL values
+/// * `negated` - Whether this is a NOT IN operation
+/// * `contains` - Closure that returns whether needle[i] is found in the haystack
+#[inline]
+fn build_in_list_result<C>(
+    len: usize,
+    needle_nulls: Option<&NullBuffer>,
+    haystack_has_nulls: bool,
+    negated: bool,
+    contains: C,
+) -> BooleanArray
+where
+    C: Fn(usize) -> bool,
+{
+    // Use collect_bool for all paths - it's vectorized and faster than element-by-element append.
+    // Match on (needle_has_nulls, haystack_has_nulls, negated) to specialize each case.
+    match (needle_nulls, haystack_has_nulls, negated) {
+        // Haystack has nulls: result is NULL when not found (might match the NULL)
+        // values_buf == nulls_buf, so compute once and clone
+        (Some(validity), true, false) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let buf = validity.inner() & &contains_buf;
+            BooleanArray::new(buf.clone(), Some(NullBuffer::new(buf)))
+        }
+        (None, true, false) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            BooleanArray::new(buf.clone(), Some(NullBuffer::new(buf)))
+        }
+        (Some(validity), true, true) => {
+            // Compute nulls_buf via SIMD AND, then derive values_buf via XOR.
+            // Uses identity: A & !B = A ^ (A & B) to get values from nulls.
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let nulls_buf = validity.inner() & &contains_buf;
+            let values_buf = validity.inner() ^ &nulls_buf; // valid & !contains
+            BooleanArray::new(values_buf, Some(NullBuffer::new(nulls_buf)))
+        }
+        (None, true, true) => {
+            // No needle nulls, but haystack has nulls
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = !&contains_buf;
+            BooleanArray::new(values_buf, Some(NullBuffer::new(contains_buf)))
+        }
+        // Only needle has nulls: nulls_buf is just validity (reuse it directly!)
+        (Some(validity), false, false) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = validity.inner() & &contains_buf;
+            BooleanArray::new(values_buf, Some(validity.clone()))
+        }
+        (Some(validity), false, true) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = validity.inner() & &(!&contains_buf);
+            BooleanArray::new(values_buf, Some(validity.clone()))
+        }
+        // No nulls anywhere: no validity buffer needed
+        (None, false, false) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            BooleanArray::new(buf, None)
+        }
+        (None, false, true) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| !contains(i));
+            BooleanArray::new(buf, None)
+        }
+    }
 }
 
-impl Int32StaticFilter {
-    fn try_new(in_array: &ArrayRef) -> Result<Self> {
-        let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+/// Sorted lookup using binary search. Best for small lists (< 8 elements).
+struct SortedLookup<T>(Vec<T>);
 
-        let mut values = HashSet::with_capacity(in_array.len());
-        let null_count = in_array.null_count();
+impl<T: Ord> SortedLookup<T> {
+    fn new(mut values: Vec<T>) -> Self {
+        values.sort_unstable();
+        values.dedup();
+        Self(values)
+    }
 
-        for v in in_array.iter().flatten() {
-            values.insert(v);
-        }
+    #[inline]
+    fn contains(&self, value: &T) -> bool {
+        self.0.binary_search(value).is_ok()

Review Comment:
   According to some googling results it can be faster up to ~128 elements, especially as it will compile to well-vectorized code for primitives https://github.com/rust-lang/rust/blob/018d26972e523b8d28f9579056185a1713949dfd/library/core/src/slice/cmp.rs#L422



##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,65 +248,414 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
-    null_count: usize,
-    values: HashSet<i32>,
+/// Threshold for switching from sorted Vec (binary search) to HashSet
+/// For small lists, binary search has better cache locality and lower overhead
+/// Maximum list size for using sorted lookup (binary search).
+/// Lists with more elements use hash lookup instead.
+const SORTED_LOOKUP_MAX_LEN: usize = 8;
+
+/// Helper to build a BooleanArray result for IN list operations.
+/// Handles SQL three-valued logic for NULL values.
+///
+/// # Arguments
+/// * `len` - Number of elements in the needle array
+/// * `needle_nulls` - Optional validity buffer from the needle array
+/// * `haystack_has_nulls` - Whether the IN list contains NULL values
+/// * `negated` - Whether this is a NOT IN operation
+/// * `contains` - Closure that returns whether needle[i] is found in the haystack
+#[inline]
+fn build_in_list_result<C>(
+    len: usize,
+    needle_nulls: Option<&NullBuffer>,
+    haystack_has_nulls: bool,
+    negated: bool,
+    contains: C,
+) -> BooleanArray
+where
+    C: Fn(usize) -> bool,
+{
+    // Use collect_bool for all paths - it's vectorized and faster than element-by-element append.
+    // Match on (needle_has_nulls, haystack_has_nulls, negated) to specialize each case.
+    match (needle_nulls, haystack_has_nulls, negated) {
+        // Haystack has nulls: result is NULL when not found (might match the NULL)
+        // values_buf == nulls_buf, so compute once and clone
+        (Some(validity), true, false) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let buf = validity.inner() & &contains_buf;
+            BooleanArray::new(buf.clone(), Some(NullBuffer::new(buf)))
+        }
+        (None, true, false) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            BooleanArray::new(buf.clone(), Some(NullBuffer::new(buf)))
+        }
+        (Some(validity), true, true) => {
+            // Compute nulls_buf via SIMD AND, then derive values_buf via XOR.
+            // Uses identity: A & !B = A ^ (A & B) to get values from nulls.
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let nulls_buf = validity.inner() & &contains_buf;
+            let values_buf = validity.inner() ^ &nulls_buf; // valid & !contains
+            BooleanArray::new(values_buf, Some(NullBuffer::new(nulls_buf)))
+        }
+        (None, true, true) => {
+            // No needle nulls, but haystack has nulls
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = !&contains_buf;
+            BooleanArray::new(values_buf, Some(NullBuffer::new(contains_buf)))
+        }
+        // Only needle has nulls: nulls_buf is just validity (reuse it directly!)
+        (Some(validity), false, false) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = validity.inner() & &contains_buf;
+            BooleanArray::new(values_buf, Some(validity.clone()))
+        }
+        (Some(validity), false, true) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = validity.inner() & &(!&contains_buf);
+            BooleanArray::new(values_buf, Some(validity.clone()))
+        }
+        // No nulls anywhere: no validity buffer needed
+        (None, false, false) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            BooleanArray::new(buf, None)
+        }
+        (None, false, true) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| !contains(i));
+            BooleanArray::new(buf, None)
+        }
+    }
 }
 
-impl Int32StaticFilter {
-    fn try_new(in_array: &ArrayRef) -> Result<Self> {
-        let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+/// Sorted lookup using binary search. Best for small lists (< 8 elements).
+struct SortedLookup<T>(Vec<T>);
 
-        let mut values = HashSet::with_capacity(in_array.len());
-        let null_count = in_array.null_count();
+impl<T: Ord> SortedLookup<T> {
+    fn new(mut values: Vec<T>) -> Self {
+        values.sort_unstable();
+        values.dedup();
+        Self(values)
+    }
 
-        for v in in_array.iter().flatten() {
-            values.insert(v);
-        }
+    #[inline]
+    fn contains(&self, value: &T) -> bool {
+        self.0.binary_search(value).is_ok()

Review Comment:
   According to some Google results it can be faster up to ~128 elements, especially as it will compile to well-vectorized code for primitives https://github.com/rust-lang/rust/blob/018d26972e523b8d28f9579056185a1713949dfd/library/core/src/slice/cmp.rs#L422



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3625983917

   Another general comment,  on the implementation this time: hashing seems overkill and probably overly expensive for small-ish simple type lists.
   
   Have you considered sorting the `InList` and doing a binary search?
   
   Even for 1024 elements in the `InList` that would be at most 10 comparisons all in L1 cache, which could be orders of magnitude faster that the overhead of hashing. To validate with the new fixed benchmarks of course!


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3637437969

   run benchmarks in_list


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3638639461

   run benchmark in_list


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3628557627

   > > Another general comment, on the implementation this time: hashing seems overkill and probably overly expensive for small simple type lists.
   > > @adriangb have you considered sorting the `InList` and doing a binary search?
   > > For small lists (threshold to be refined...) this could be orders of magnitude faster that the overhead of hashing. To validate with the new fixed benchmarks of course!
   > 
   > I think that's a really neat idea! I did look into using binary search at some point (not this PR) but then realized that there was already the hashing in place and didn't pursue it further. So while I agree it could be interesting to have two approaches, I think we should focus on improving the current approach right now especially since we probably degraded performance since last release. Maybe let's file a ticket to track benchmarking that approach?
   
   This was too much fun to skip the opportunity! I've opened a draft PR on your branch that shows pretty cool results: https://github.com/pydantic/datafusion/pull/46


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3643591597

   run benchmark clickbench_partitioned tpch


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3637312773

   > @Dandandan is already on the list https://github.com/alamb/datafusion-benchmarking/blob/4fb120785fa66ecbf40a45d8a5d0d5f4be17266a/scripts/scrape_comments.py#L41
   > 
   > I can add @geoffreyclaude if he would like
   
   @alamb yes please :) Especially for when/if I follow through with the additional perf improvements.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on code in PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#discussion_r2612258575


##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -138,9 +142,20 @@ fn instantiate_static_filter(
     in_array: ArrayRef,
 ) -> Result<Arc<dyn StaticFilter + Send + Sync>> {
     match in_array.data_type() {
+        // Integer primitive types
+        DataType::Int8 => Ok(Arc::new(Int8StaticFilter::try_new(&in_array)?)),
+        DataType::Int16 => Ok(Arc::new(Int16StaticFilter::try_new(&in_array)?)),
         DataType::Int32 => Ok(Arc::new(Int32StaticFilter::try_new(&in_array)?)),
+        DataType::Int64 => Ok(Arc::new(Int64StaticFilter::try_new(&in_array)?)),
+        DataType::UInt8 => Ok(Arc::new(UInt8StaticFilter::try_new(&in_array)?)),
+        DataType::UInt16 => Ok(Arc::new(UInt16StaticFilter::try_new(&in_array)?)),
+        DataType::UInt32 => Ok(Arc::new(UInt32StaticFilter::try_new(&in_array)?)),
+        DataType::UInt64 => Ok(Arc::new(UInt64StaticFilter::try_new(&in_array)?)),
+        // Float primitive types (use ordered wrappers for Hash/Eq)
+        DataType::Float32 => Ok(Arc::new(Float32StaticFilter::try_new(&in_array)?)),
+        DataType::Float64 => Ok(Arc::new(Float64StaticFilter::try_new(&in_array)?)),

Review Comment:
   No but I don't think that was optimized before and there's less opportunity to optimize because of the copy price. I'm going to leave that for https://github.com/apache/datafusion/issues/19241 where there's already a lot of great ideas if that's okay



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "alamb-ghbot (via GitHub)" <gi...@apache.org>.
alamb-ghbot commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3643823110

   🤖 `./gh_compare_branch.sh` [gh_compare_branch.sh](https://github.com/alamb/datafusion-benchmarking/blob/main/scripts/gh_compare_branch.sh) Running
   Linux aal-dev 6.14.0-1018-gcp #19~24.04.1-Ubuntu SMP Wed Sep 24 23:23:09 UTC 2025 x86_64 x86_64 x86_64 GNU/Linux
   Comparing specialize (b6404e5bcd119782d08853095c1bd7f9943d5893) to e8a0829b7a2044ab477784d60ed2d208b97f5042 [diff](https://github.com/apache/datafusion/compare/e8a0829b7a2044ab477784d60ed2d208b97f5042..b6404e5bcd119782d08853095c1bd7f9943d5893) using:  tpch
   Results will be posted here when complete
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "alamb-ghbot (via GitHub)" <gi...@apache.org>.
alamb-ghbot commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3634535976

   🤖 Hi @adriangb, thanks for the request (https://github.com/apache/datafusion/pull/18832#issuecomment-3634468395).
   
   [`scrape_comments.py`](https://github.com/alamb/datafusion-benchmarking/blob/main/scripts/scrape_comments.py) only supports whitelisted benchmarks.
   - Standard: clickbench_1, clickbench_extended, clickbench_partitioned, clickbench_pushdown, tpch, tpch10, tpch_mem, tpch_mem10
   - Criterion: aggregate_query_sql, aggregate_vectorized, case_when, in_list, sql_planner
   
   Please choose one or more of these with `run benchmark <name>` or `run benchmark <name1> <name2>...`


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3556463494

   Thinking about it the trick is probably to avoid the extra `to_string()`/`to_vec()` allocation and store just the hashes. Will look into that.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "Dandandan (via GitHub)" <gi...@apache.org>.
Dandandan commented on code in PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#discussion_r2549501179


##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,68 +206,122 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
-    null_count: usize,
-    values: HashSet<i32>,
-}
+// Macro to generate specialized StaticFilter implementations for primitive types
+macro_rules! primitive_static_filter {
+    ($Name:ident, $ArrowType:ty) => {
+        struct $Name {
+            null_count: usize,
+            values: HashSet<<$ArrowType as ArrowPrimitiveType>::Native>,
+        }
 
-impl Int32StaticFilter {
-    fn try_new(in_array: &ArrayRef) -> Result<Self> {
-        let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+        impl $Name {
+            fn try_new(in_array: &ArrayRef) -> Result<Self> {
+                let in_array = in_array
+                    .as_primitive_opt::<$ArrowType>()
+                    .ok_or_else(|| exec_datafusion_err!(format!("Failed to downcast an array to a '{}' array", stringify!($ArrowType))))?;
 
-        let mut values = HashSet::with_capacity(in_array.len());
-        let null_count = in_array.null_count();
+                let mut values = HashSet::with_capacity(in_array.len());
+                let null_count = in_array.null_count();
+
+                for v in in_array.iter().flatten() {
+                    values.insert(v);
+                }
 
-        for v in in_array.iter().flatten() {
-            values.insert(v);
+                Ok(Self { null_count, values })
+            }
         }
 
-        Ok(Self { null_count, values })
-    }
-}
+        impl StaticFilter for $Name {
+            fn null_count(&self) -> usize {
+                self.null_count
+            }
 
-impl StaticFilter for Int32StaticFilter {
-    fn null_count(&self) -> usize {
-        self.null_count
-    }
+            fn contains(&self, v: &dyn Array, negated: bool) -> Result<BooleanArray> {
+                // Handle dictionary arrays by recursing on the values
+                downcast_dictionary_array! {
+                    v => {
+                        let values_contains = self.contains(v.values().as_ref(), negated)?;
+                        let result = take(&values_contains, v.keys(), None)?;
+                        return Ok(downcast_array(result.as_ref()))
+                    }
+                    _ => {}
+                }
 
-    fn contains(&self, v: &dyn Array, negated: bool) -> Result<BooleanArray> {
-        let v = v
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
-
-        let result = match (v.null_count() > 0, negated) {
-            (true, false) => {
-                // has nulls, not negated"
-                BooleanArray::from_iter(
-                    v.iter().map(|value| Some(self.values.contains(&value?))),
-                )
-            }
-            (true, true) => {
-                // has nulls, negated
-                BooleanArray::from_iter(
-                    v.iter().map(|value| Some(!self.values.contains(&value?))),
-                )
-            }
-            (false, false) => {
-                //no null, not negated
-                BooleanArray::from_iter(
-                    v.values().iter().map(|value| self.values.contains(value)),
-                )
-            }
-            (false, true) => {
-                // no null, negated
-                BooleanArray::from_iter(
-                    v.values().iter().map(|value| !self.values.contains(value)),
-                )
+                let v = v
+                    .as_primitive_opt::<$ArrowType>()
+                    .ok_or_else(|| exec_datafusion_err!(format!("Failed to downcast an array to a '{}' array", stringify!($ArrowType))))?;
+
+                let haystack_has_nulls = self.null_count > 0;
+
+                let result = match (v.null_count() > 0, haystack_has_nulls, negated) {
+                    (true, _, false) | (false, true, false) => {
+                        // Either needle or haystack has nulls, not negated
+                        BooleanArray::from_iter(v.iter().map(|value| {

Review Comment:
   `BooleanArray::collect_bool` is much faster



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3628202913

   > Another general comment, on the implementation this time: hashing seems overkill and probably overly expensive for small simple type lists.
   > 
   > @adriangb have you considered sorting the `InList` and doing a binary search?
   > 
   > For small lists (threshold to be refined...) this could be orders of magnitude faster that the overhead of hashing. To validate with the new fixed benchmarks of course!
   
   I think that's a really neat idea! I did look into using binary search at some point (not this PR) but then realized that there was already the hashing in place and didn't pursue it further. So while I agree it could be interesting to have two approaches, I think we should focus on improving the current approach right now especially since we probably degraded performance since last release. Maybe let's file a ticket to track benchmarking that approach?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3555171254

   @alamb maybe let's run benchmarks?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "Dandandan (via GitHub)" <gi...@apache.org>.
Dandandan commented on code in PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#discussion_r2549507569


##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,68 +206,122 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
-    null_count: usize,
-    values: HashSet<i32>,
-}
+// Macro to generate specialized StaticFilter implementations for primitive types
+macro_rules! primitive_static_filter {
+    ($Name:ident, $ArrowType:ty) => {
+        struct $Name {
+            null_count: usize,
+            values: HashSet<<$ArrowType as ArrowPrimitiveType>::Native>,
+        }
 
-impl Int32StaticFilter {
-    fn try_new(in_array: &ArrayRef) -> Result<Self> {
-        let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+        impl $Name {
+            fn try_new(in_array: &ArrayRef) -> Result<Self> {
+                let in_array = in_array
+                    .as_primitive_opt::<$ArrowType>()
+                    .ok_or_else(|| exec_datafusion_err!(format!("Failed to downcast an array to a '{}' array", stringify!($ArrowType))))?;
 
-        let mut values = HashSet::with_capacity(in_array.len());
-        let null_count = in_array.null_count();
+                let mut values = HashSet::with_capacity(in_array.len());
+                let null_count = in_array.null_count();
+
+                for v in in_array.iter().flatten() {
+                    values.insert(v);
+                }
 
-        for v in in_array.iter().flatten() {
-            values.insert(v);
+                Ok(Self { null_count, values })
+            }
         }
 
-        Ok(Self { null_count, values })
-    }
-}
+        impl StaticFilter for $Name {
+            fn null_count(&self) -> usize {
+                self.null_count
+            }
 
-impl StaticFilter for Int32StaticFilter {
-    fn null_count(&self) -> usize {
-        self.null_count
-    }
+            fn contains(&self, v: &dyn Array, negated: bool) -> Result<BooleanArray> {
+                // Handle dictionary arrays by recursing on the values
+                downcast_dictionary_array! {
+                    v => {
+                        let values_contains = self.contains(v.values().as_ref(), negated)?;
+                        let result = take(&values_contains, v.keys(), None)?;
+                        return Ok(downcast_array(result.as_ref()))
+                    }
+                    _ => {}
+                }
 
-    fn contains(&self, v: &dyn Array, negated: bool) -> Result<BooleanArray> {
-        let v = v
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
-
-        let result = match (v.null_count() > 0, negated) {
-            (true, false) => {
-                // has nulls, not negated"
-                BooleanArray::from_iter(
-                    v.iter().map(|value| Some(self.values.contains(&value?))),
-                )
-            }
-            (true, true) => {
-                // has nulls, negated
-                BooleanArray::from_iter(
-                    v.iter().map(|value| Some(!self.values.contains(&value?))),
-                )
-            }
-            (false, false) => {
-                //no null, not negated
-                BooleanArray::from_iter(
-                    v.values().iter().map(|value| self.values.contains(value)),
-                )
-            }
-            (false, true) => {
-                // no null, negated
-                BooleanArray::from_iter(
-                    v.values().iter().map(|value| !self.values.contains(value)),
-                )
+                let v = v
+                    .as_primitive_opt::<$ArrowType>()
+                    .ok_or_else(|| exec_datafusion_err!(format!("Failed to downcast an array to a '{}' array", stringify!($ArrowType))))?;
+
+                let haystack_has_nulls = self.null_count > 0;
+
+                let result = match (v.null_count() > 0, haystack_has_nulls, negated) {
+                    (true, _, false) | (false, true, false) => {
+                        // Either needle or haystack has nulls, not negated
+                        BooleanArray::from_iter(v.iter().map(|value| {
+                            match value {
+                                // SQL three-valued logic: null IN (...) is always null
+                                None => None,
+                                Some(v) => {
+                                    if self.values.contains(&v) {
+                                        Some(true)
+                                    } else if haystack_has_nulls {
+                                        // value not in set, but set has nulls -> null
+                                        None
+                                    } else {
+                                        Some(false)
+                                    }
+                                }
+                            }
+                        }))
+                    }
+                    (true, _, true) | (false, true, true) => {
+                        // Either needle or haystack has nulls, negated
+                        BooleanArray::from_iter(v.iter().map(|value| {
+                            match value {
+                                // SQL three-valued logic: null NOT IN (...) is always null
+                                None => None,
+                                Some(v) => {
+                                    if self.values.contains(&v) {
+                                        Some(false)
+                                    } else if haystack_has_nulls {
+                                        // value not in set, but set has nulls -> null
+                                        None
+                                    } else {
+                                        Some(true)
+                                    }
+                                }
+                            }
+                        }))
+                    }
+                    (false, false, false) => {
+                        // no nulls anywhere, not negated
+                        BooleanArray::from_iter(

Review Comment:
   `BooleanArray::collect_bool is faster`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3566677313

   🤖 `./gh_compare_branch_bench.sh` [Benchmark Script](https://github.com/alamb/datafusion-benchmarking/blob/main/gh_compare_branch_bench.sh) Running
   Linux aal-dev 6.14.0-1018-gcp #19~24.04.1-Ubuntu SMP Wed Sep 24 23:23:09 UTC 2025 x86_64 x86_64 x86_64 GNU/Linux
   Comparing specialize (1e4782f1cde36a83398002a4730ff96123b547a3) to 7d8b8602ad1be2f61f6a8ebb253ace9d85304ea7 [diff](https://github.com/apache/datafusion/compare/7d8b8602ad1be2f61f6a8ebb253ace9d85304ea7..1e4782f1cde36a83398002a4730ff96123b547a3)
   BENCH_NAME=in_list
   BENCH_COMMAND=cargo bench --bench in_list
   BENCH_FILTER=
   BENCH_BRANCH_NAME=specialize
   Results will be posted here when complete
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3638509684

   Seems reproducible 😄 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#discussion_r2610778034


##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,99 +213,302 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
-    null_count: usize,
-    values: HashSet<i32>,
+/// Wrapper for f32 that implements Hash and Eq using IEEE 754 total ordering.
+/// This treats NaN values as equal to each other (using total_cmp).
+#[derive(Clone, Copy)]
+struct OrderedFloat32(f32);
+
+impl Hash for OrderedFloat32 {
+    fn hash<H: Hasher>(&self, state: &mut H) {
+        self.0.to_ne_bytes().hash(state);
+    }
 }
 
-impl Int32StaticFilter {
-    fn try_new(in_array: &ArrayRef) -> Result<Self> {
-        let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+impl PartialEq for OrderedFloat32 {
+    fn eq(&self, other: &Self) -> bool {
+        self.0.total_cmp(&other.0).is_eq()
+    }
+}
 
-        let mut values = HashSet::with_capacity(in_array.len());
-        let null_count = in_array.null_count();
+impl Eq for OrderedFloat32 {}
 
-        for v in in_array.iter().flatten() {
-            values.insert(v);
-        }
+impl From<f32> for OrderedFloat32 {
+    fn from(v: f32) -> Self {
+        Self(v)
+    }
+}
 
-        Ok(Self { null_count, values })
+/// Wrapper for f64 that implements Hash and Eq using IEEE 754 total ordering.
+/// This treats NaN values as equal to each other (using total_cmp).
+#[derive(Clone, Copy)]
+struct OrderedFloat64(f64);
+
+impl Hash for OrderedFloat64 {
+    fn hash<H: Hasher>(&self, state: &mut H) {
+        self.0.to_ne_bytes().hash(state);
     }
 }
 
-impl StaticFilter for Int32StaticFilter {
-    fn null_count(&self) -> usize {
-        self.null_count
+impl PartialEq for OrderedFloat64 {
+    fn eq(&self, other: &Self) -> bool {
+        self.0.total_cmp(&other.0).is_eq()
     }
+}
 
-    fn contains(&self, v: &dyn Array, negated: bool) -> Result<BooleanArray> {
-        // Handle dictionary arrays by recursing on the values
-        downcast_dictionary_array! {
-            v => {
-                let values_contains = self.contains(v.values().as_ref(), negated)?;
-                let result = take(&values_contains, v.keys(), None)?;
-                return Ok(downcast_array(result.as_ref()))
+impl Eq for OrderedFloat64 {}
+
+impl From<f64> for OrderedFloat64 {
+    fn from(v: f64) -> Self {
+        Self(v)
+    }
+}
+
+// Macro to generate specialized StaticFilter implementations for primitive types
+macro_rules! primitive_static_filter {
+    ($Name:ident, $ArrowType:ty) => {
+        struct $Name {
+            null_count: usize,
+            values: HashSet<<$ArrowType as ArrowPrimitiveType>::Native>,
+        }
+
+        impl $Name {
+            fn try_new(in_array: &ArrayRef) -> Result<Self> {
+                let in_array = in_array
+                    .as_primitive_opt::<$ArrowType>()
+                    .ok_or_else(|| exec_datafusion_err!("Failed to downcast an array to a '{}' array", stringify!($ArrowType)))?;
+
+                let mut values = HashSet::with_capacity(in_array.len());
+                let null_count = in_array.null_count();
+
+                for v in in_array.iter().flatten() {
+                    values.insert(v);
+                }
+
+                Ok(Self { null_count, values })
             }
-            _ => {}
         }
 
-        let v = v
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
-
-        let haystack_has_nulls = self.null_count > 0;
-        let has_nulls = v.null_count() > 0 || haystack_has_nulls;
-
-        let result = match (has_nulls, negated) {
-            (true, false) => {
-                // needle has nulls, not negated
-                BooleanArray::from_iter(v.iter().map(|value| match value {
-                    None => None,
-                    Some(v) => {
-                        if self.values.contains(&v) {
-                            Some(true)
-                        } else if haystack_has_nulls {
-                            None
+        impl StaticFilter for $Name {
+            fn null_count(&self) -> usize {
+                self.null_count
+            }
+
+            fn contains(&self, v: &dyn Array, negated: bool) -> Result<BooleanArray> {
+                // Handle dictionary arrays by recursing on the values
+                downcast_dictionary_array! {
+                    v => {
+                        let values_contains = self.contains(v.values().as_ref(), negated)?;
+                        let result = take(&values_contains, v.keys(), None)?;
+                        return Ok(downcast_array(result.as_ref()))
+                    }
+                    _ => {}
+                }
+
+                let v = v
+                    .as_primitive_opt::<$ArrowType>()
+                    .ok_or_else(|| exec_datafusion_err!("Failed to downcast an array to a '{}' array", stringify!($ArrowType)))?;
+
+                let haystack_has_nulls = self.null_count > 0;
+
+                let needle_values = v.values();
+                let needle_nulls = v.nulls();
+                let needle_has_nulls = v.null_count() > 0;
+
+                // Compute the "contains" result using collect_bool (fast batched approach)
+                // This ignores nulls - we handle them separately
+                let contains_buffer = if negated {
+                    BooleanBuffer::collect_bool(needle_values.len(), |i| {
+                        !self.values.contains(&needle_values[i])
+                    })
+                } else {
+                    BooleanBuffer::collect_bool(needle_values.len(), |i| {
+                        self.values.contains(&needle_values[i])
+                    })
+                };
+
+                // Compute the null mask
+                // Output is null when:
+                // 1. needle value is null, OR
+                // 2. needle value is not in set AND haystack has nulls
+                let result_nulls = match (needle_has_nulls, haystack_has_nulls) {
+                    (false, false) => {
+                        // No nulls anywhere
+                        None
+                    }
+                    (true, false) => {
+                        // Only needle has nulls - just use needle's null mask
+                        needle_nulls.cloned()
+                    }
+                    (false, true) => {
+                        // Only haystack has nulls - null where not-in-set

Review Comment:
   This comment block is a bit verbose and not super clear. Maybe having it in table form would help?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#discussion_r2603433605


##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,65 +248,414 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
-    null_count: usize,
-    values: HashSet<i32>,
+/// Threshold for switching from sorted Vec (binary search) to HashSet
+/// For small lists, binary search has better cache locality and lower overhead
+/// Maximum list size for using sorted lookup (binary search).
+/// Lists with more elements use hash lookup instead.
+const SORTED_LOOKUP_MAX_LEN: usize = 8;
+
+/// Helper to build a BooleanArray result for IN list operations.
+/// Handles SQL three-valued logic for NULL values.
+///
+/// # Arguments
+/// * `len` - Number of elements in the needle array
+/// * `needle_nulls` - Optional validity buffer from the needle array
+/// * `haystack_has_nulls` - Whether the IN list contains NULL values
+/// * `negated` - Whether this is a NOT IN operation
+/// * `contains` - Closure that returns whether needle[i] is found in the haystack
+#[inline]
+fn build_in_list_result<C>(
+    len: usize,
+    needle_nulls: Option<&NullBuffer>,
+    haystack_has_nulls: bool,
+    negated: bool,
+    contains: C,
+) -> BooleanArray
+where
+    C: Fn(usize) -> bool,
+{
+    // Use collect_bool for all paths - it's vectorized and faster than element-by-element append.
+    // Match on (needle_has_nulls, haystack_has_nulls, negated) to specialize each case.
+    match (needle_nulls, haystack_has_nulls, negated) {
+        // Haystack has nulls: result is NULL when not found (might match the NULL)
+        // values_buf == nulls_buf, so compute once and clone
+        (Some(validity), true, false) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let buf = validity.inner() & &contains_buf;
+            BooleanArray::new(buf.clone(), Some(NullBuffer::new(buf)))
+        }
+        (None, true, false) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            BooleanArray::new(buf.clone(), Some(NullBuffer::new(buf)))
+        }
+        (Some(validity), true, true) => {
+            // Compute nulls_buf via SIMD AND, then derive values_buf via XOR.
+            // Uses identity: A & !B = A ^ (A & B) to get values from nulls.
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let nulls_buf = validity.inner() & &contains_buf;
+            let values_buf = validity.inner() ^ &nulls_buf; // valid & !contains
+            BooleanArray::new(values_buf, Some(NullBuffer::new(nulls_buf)))
+        }
+        (None, true, true) => {
+            // No needle nulls, but haystack has nulls
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = !&contains_buf;
+            BooleanArray::new(values_buf, Some(NullBuffer::new(contains_buf)))
+        }
+        // Only needle has nulls: nulls_buf is just validity (reuse it directly!)
+        (Some(validity), false, false) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = validity.inner() & &contains_buf;
+            BooleanArray::new(values_buf, Some(validity.clone()))
+        }
+        (Some(validity), false, true) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = validity.inner() & &(!&contains_buf);
+            BooleanArray::new(values_buf, Some(validity.clone()))
+        }
+        // No nulls anywhere: no validity buffer needed
+        (None, false, false) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            BooleanArray::new(buf, None)
+        }
+        (None, false, true) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| !contains(i));
+            BooleanArray::new(buf, None)
+        }
+    }
 }
 
-impl Int32StaticFilter {
-    fn try_new(in_array: &ArrayRef) -> Result<Self> {
-        let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+/// Sorted lookup using binary search. Best for small lists (< 8 elements).
+struct SortedLookup<T>(Vec<T>);
 
-        let mut values = HashSet::with_capacity(in_array.len());
-        let null_count = in_array.null_count();
+impl<T: Ord> SortedLookup<T> {
+    fn new(mut values: Vec<T>) -> Self {
+        values.sort_unstable();
+        values.dedup();
+        Self(values)
+    }
 
-        for v in in_array.iter().flatten() {
-            values.insert(v);
-        }
+    #[inline]
+    fn contains(&self, value: &T) -> bool {
+        self.0.binary_search(value).is_ok()

Review Comment:
   > smaller targeted PRs off of that
   
   That's definitely the way to go! I'll fork off an issue from https://github.com/apache/datafusion/issues/18824.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#discussion_r2603681481


##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,65 +248,414 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
-    null_count: usize,
-    values: HashSet<i32>,
+/// Threshold for switching from sorted Vec (binary search) to HashSet
+/// For small lists, binary search has better cache locality and lower overhead
+/// Maximum list size for using sorted lookup (binary search).
+/// Lists with more elements use hash lookup instead.
+const SORTED_LOOKUP_MAX_LEN: usize = 8;
+
+/// Helper to build a BooleanArray result for IN list operations.
+/// Handles SQL three-valued logic for NULL values.
+///
+/// # Arguments
+/// * `len` - Number of elements in the needle array
+/// * `needle_nulls` - Optional validity buffer from the needle array
+/// * `haystack_has_nulls` - Whether the IN list contains NULL values
+/// * `negated` - Whether this is a NOT IN operation
+/// * `contains` - Closure that returns whether needle[i] is found in the haystack
+#[inline]
+fn build_in_list_result<C>(
+    len: usize,
+    needle_nulls: Option<&NullBuffer>,
+    haystack_has_nulls: bool,
+    negated: bool,
+    contains: C,
+) -> BooleanArray
+where
+    C: Fn(usize) -> bool,
+{
+    // Use collect_bool for all paths - it's vectorized and faster than element-by-element append.
+    // Match on (needle_has_nulls, haystack_has_nulls, negated) to specialize each case.
+    match (needle_nulls, haystack_has_nulls, negated) {
+        // Haystack has nulls: result is NULL when not found (might match the NULL)
+        // values_buf == nulls_buf, so compute once and clone
+        (Some(validity), true, false) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let buf = validity.inner() & &contains_buf;
+            BooleanArray::new(buf.clone(), Some(NullBuffer::new(buf)))
+        }
+        (None, true, false) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            BooleanArray::new(buf.clone(), Some(NullBuffer::new(buf)))
+        }
+        (Some(validity), true, true) => {
+            // Compute nulls_buf via SIMD AND, then derive values_buf via XOR.
+            // Uses identity: A & !B = A ^ (A & B) to get values from nulls.
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let nulls_buf = validity.inner() & &contains_buf;
+            let values_buf = validity.inner() ^ &nulls_buf; // valid & !contains
+            BooleanArray::new(values_buf, Some(NullBuffer::new(nulls_buf)))
+        }
+        (None, true, true) => {
+            // No needle nulls, but haystack has nulls
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = !&contains_buf;
+            BooleanArray::new(values_buf, Some(NullBuffer::new(contains_buf)))
+        }
+        // Only needle has nulls: nulls_buf is just validity (reuse it directly!)
+        (Some(validity), false, false) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = validity.inner() & &contains_buf;
+            BooleanArray::new(values_buf, Some(validity.clone()))
+        }
+        (Some(validity), false, true) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = validity.inner() & &(!&contains_buf);
+            BooleanArray::new(values_buf, Some(validity.clone()))
+        }
+        // No nulls anywhere: no validity buffer needed
+        (None, false, false) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            BooleanArray::new(buf, None)
+        }
+        (None, false, true) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| !contains(i));
+            BooleanArray::new(buf, None)
+        }
+    }
 }
 
-impl Int32StaticFilter {
-    fn try_new(in_array: &ArrayRef) -> Result<Self> {
-        let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+/// Sorted lookup using binary search. Best for small lists (< 8 elements).
+struct SortedLookup<T>(Vec<T>);
 
-        let mut values = HashSet::with_capacity(in_array.len());
-        let null_count = in_array.null_count();
+impl<T: Ord> SortedLookup<T> {
+    fn new(mut values: Vec<T>) -> Self {
+        values.sort_unstable();
+        values.dedup();
+        Self(values)
+    }
 
-        for v in in_array.iter().flatten() {
-            values.insert(v);
-        }
+    #[inline]
+    fn contains(&self, value: &T) -> bool {
+        self.0.binary_search(value).is_ok()

Review Comment:
   Yes, you should probably just revert my commit



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "alamb-ghbot (via GitHub)" <gi...@apache.org>.
alamb-ghbot commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3638336057

   🤖 `./gh_compare_branch_bench.sh` [compare_branch_bench.sh](https://github.com/alamb/datafusion-benchmarking/blob/main/scripts/compare_branch_bench.sh) Running
   Linux aal-dev 6.14.0-1018-gcp #19~24.04.1-Ubuntu SMP Wed Sep 24 23:23:09 UTC 2025 x86_64 x86_64 x86_64 GNU/Linux
   Comparing specialize (a430ef82c3fd5ca97dab917659f43d7e663b6fa6) to e8a0829b7a2044ab477784d60ed2d208b97f5042 [diff](https://github.com/apache/datafusion/compare/e8a0829b7a2044ab477784d60ed2d208b97f5042..a430ef82c3fd5ca97dab917659f43d7e663b6fa6)
   BENCH_NAME=in_list
   BENCH_COMMAND=cargo bench --all-features --bench in_list
   BENCH_FILTER=
   BENCH_BRANCH_NAME=specialize
   Results will be posted here when complete
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "alamb-ghbot (via GitHub)" <gi...@apache.org>.
alamb-ghbot commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3638709380

   🤖: Benchmark completed
   
   <details><summary>Details</summary>
   <p>
   
   
   ```
   group                                          main                                   specialize
   -----                                          ----                                   ----------
   in_list/Float32/list=100/nulls=0%              51.58   306.7±2.41µs        ? ?/sec    1.00      5.9±0.08µs        ? ?/sec
   in_list/Float32/list=100/nulls=20%             55.98   390.8±2.57µs        ? ?/sec    1.00      7.0±0.06µs        ? ?/sec
   in_list/Float32/list=3/nulls=0%                2.68     14.6±0.20µs        ? ?/sec    1.00      5.4±0.19µs        ? ?/sec
   in_list/Float32/list=3/nulls=20%               3.44     19.8±0.76µs        ? ?/sec    1.00      5.8±0.02µs        ? ?/sec
   in_list/Float32/list=8/nulls=0%                5.06     29.0±0.46µs        ? ?/sec    1.00      5.7±0.06µs        ? ?/sec
   in_list/Float32/list=8/nulls=20%               6.95     39.2±0.35µs        ? ?/sec    1.00      5.6±0.21µs        ? ?/sec
   in_list/Int32/list=100/nulls=0%                1.34      6.0±0.13µs        ? ?/sec    1.00      4.5±0.04µs        ? ?/sec
   in_list/Int32/list=100/nulls=20%               1.90      8.2±0.21µs        ? ?/sec    1.00      4.3±0.13µs        ? ?/sec
   in_list/Int32/list=3/nulls=0%                  1.43      6.0±0.30µs        ? ?/sec    1.00      4.2±0.03µs        ? ?/sec
   in_list/Int32/list=3/nulls=20%                 2.15      8.6±0.04µs        ? ?/sec    1.00      4.0±0.01µs        ? ?/sec
   in_list/Int32/list=8/nulls=0%                  1.45      6.0±0.13µs        ? ?/sec    1.00      4.1±0.03µs        ? ?/sec
   in_list/Int32/list=8/nulls=20%                 1.91      8.4±0.26µs        ? ?/sec    1.00      4.4±0.05µs        ? ?/sec
   in_list/Utf8/list=100/nulls=0%/str=100         1.00   642.9±18.69µs        ? ?/sec    1.00   643.3±15.52µs        ? ?/sec
   in_list/Utf8/list=100/nulls=0%/str=12          1.06   711.3±40.52µs        ? ?/sec    1.00    669.0±5.52µs        ? ?/sec
   in_list/Utf8/list=100/nulls=0%/str=3           1.04   699.0±45.42µs        ? ?/sec    1.00   672.0±13.27µs        ? ?/sec
   in_list/Utf8/list=100/nulls=20%/str=100        1.00    596.0±5.59µs        ? ?/sec    1.02   606.4±27.65µs        ? ?/sec
   in_list/Utf8/list=100/nulls=20%/str=12         1.01    624.1±5.11µs        ? ?/sec    1.00   618.7±19.97µs        ? ?/sec
   in_list/Utf8/list=100/nulls=20%/str=3          1.00    621.0±4.63µs        ? ?/sec    1.00   619.1±14.66µs        ? ?/sec
   in_list/Utf8/list=3/nulls=0%/str=100           1.08     28.3±1.39µs        ? ?/sec    1.00     26.2±0.23µs        ? ?/sec
   in_list/Utf8/list=3/nulls=0%/str=12            1.06     27.4±0.06µs        ? ?/sec    1.00     25.8±0.30µs        ? ?/sec
   in_list/Utf8/list=3/nulls=0%/str=3             1.09     29.6±2.53µs        ? ?/sec    1.00     27.2±1.82µs        ? ?/sec
   in_list/Utf8/list=3/nulls=20%/str=100          1.01     26.6±0.32µs        ? ?/sec    1.00     26.4±0.19µs        ? ?/sec
   in_list/Utf8/list=3/nulls=20%/str=12           1.06     28.6±1.18µs        ? ?/sec    1.00     27.1±0.34µs        ? ?/sec
   in_list/Utf8/list=3/nulls=20%/str=3            1.02     27.6±0.61µs        ? ?/sec    1.00     27.2±0.36µs        ? ?/sec
   in_list/Utf8/list=8/nulls=0%/str=100           1.05     58.5±3.52µs        ? ?/sec    1.00     55.8±0.98µs        ? ?/sec
   in_list/Utf8/list=8/nulls=0%/str=12            1.11     63.7±0.38µs        ? ?/sec    1.00     57.1±0.21µs        ? ?/sec
   in_list/Utf8/list=8/nulls=0%/str=3             1.20     69.2±4.84µs        ? ?/sec    1.00     57.5±0.19µs        ? ?/sec
   in_list/Utf8/list=8/nulls=20%/str=100          1.00     53.3±0.93µs        ? ?/sec    1.02     54.3±1.38µs        ? ?/sec
   in_list/Utf8/list=8/nulls=20%/str=12           1.00     53.4±0.53µs        ? ?/sec    1.01     54.1±1.05µs        ? ?/sec
   in_list/Utf8/list=8/nulls=20%/str=3            1.01     55.0±0.67µs        ? ?/sec    1.00     54.6±2.05µs        ? ?/sec
   in_list/Utf8View/list=100/nulls=0%/str=100     1.00    595.2±7.31µs        ? ?/sec    1.05    623.5±9.42µs        ? ?/sec
   in_list/Utf8View/list=100/nulls=0%/str=12      1.00   578.4±17.29µs        ? ?/sec    1.00   577.7±11.62µs        ? ?/sec
   in_list/Utf8View/list=100/nulls=0%/str=3       1.00    578.5±5.77µs        ? ?/sec    1.04  600.3±110.42µs        ? ?/sec
   in_list/Utf8View/list=100/nulls=20%/str=100    1.00    502.9±4.92µs        ? ?/sec    1.05    527.1±5.38µs        ? ?/sec
   in_list/Utf8View/list=100/nulls=20%/str=12     1.00    511.5±8.06µs        ? ?/sec    1.00    509.0±2.38µs        ? ?/sec
   in_list/Utf8View/list=100/nulls=20%/str=3      1.00    516.9±7.43µs        ? ?/sec    1.00    515.2±5.38µs        ? ?/sec
   in_list/Utf8View/list=3/nulls=0%/str=100       1.04     22.2±0.28µs        ? ?/sec    1.00     21.3±0.80µs        ? ?/sec
   in_list/Utf8View/list=3/nulls=0%/str=12        1.04     23.3±0.89µs        ? ?/sec    1.00     22.4±0.41µs        ? ?/sec
   in_list/Utf8View/list=3/nulls=0%/str=3         1.04     23.2±0.20µs        ? ?/sec    1.00     22.2±0.08µs        ? ?/sec
   in_list/Utf8View/list=3/nulls=20%/str=100      1.01     23.0±0.14µs        ? ?/sec    1.00     22.8±0.83µs        ? ?/sec
   in_list/Utf8View/list=3/nulls=20%/str=12       1.01     23.4±0.18µs        ? ?/sec    1.00     23.1±1.01µs        ? ?/sec
   in_list/Utf8View/list=3/nulls=20%/str=3        1.02     23.7±0.17µs        ? ?/sec    1.00     23.1±0.57µs        ? ?/sec
   in_list/Utf8View/list=8/nulls=0%/str=100       1.00     48.9±1.12µs        ? ?/sec    1.01     49.5±0.84µs        ? ?/sec
   in_list/Utf8View/list=8/nulls=0%/str=12        1.02     50.6±0.33µs        ? ?/sec    1.00     49.4±0.55µs        ? ?/sec
   in_list/Utf8View/list=8/nulls=0%/str=3         1.03     50.6±0.68µs        ? ?/sec    1.00     49.4±0.15µs        ? ?/sec
   in_list/Utf8View/list=8/nulls=20%/str=100      1.00     44.9±0.61µs        ? ?/sec    1.02     45.7±0.52µs        ? ?/sec
   in_list/Utf8View/list=8/nulls=20%/str=12       1.00     46.1±0.27µs        ? ?/sec    1.00     45.9±0.54µs        ? ?/sec
   in_list/Utf8View/list=8/nulls=20%/str=3        1.01     48.3±0.30µs        ? ?/sec    1.00     47.8±0.78µs        ? ?/sec
   ```
   
   
   </p>
   </details>
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3643535782

   The benchmarks are now looking *very* good, and this has gone through several rounds of review, all of it addressed. But there are significant changes since the last approvals. @geoffreyclaude could you give another review and approve if you think it's ready so we can merge this piece and continue work in https://github.com/apache/datafusion/issues/19241


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "alamb-ghbot (via GitHub)" <gi...@apache.org>.
alamb-ghbot commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3643723796

   🤖 `./gh_compare_branch.sh` [gh_compare_branch.sh](https://github.com/alamb/datafusion-benchmarking/blob/main/scripts/gh_compare_branch.sh) Running
   Linux aal-dev 6.14.0-1018-gcp #19~24.04.1-Ubuntu SMP Wed Sep 24 23:23:09 UTC 2025 x86_64 x86_64 x86_64 GNU/Linux
   Comparing specialize (b6404e5bcd119782d08853095c1bd7f9943d5893) to e8a0829b7a2044ab477784d60ed2d208b97f5042 [diff](https://github.com/apache/datafusion/compare/e8a0829b7a2044ab477784d60ed2d208b97f5042..b6404e5bcd119782d08853095c1bd7f9943d5893) using:  clickbench_partitioned
   Results will be posted here when complete
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "alamb-ghbot (via GitHub)" <gi...@apache.org>.
alamb-ghbot commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3643822944

   🤖: Benchmark completed
   
   <details><summary>Details</summary>
   <p>
   
   
   ```
   Comparing HEAD and specialize
   --------------------
   Benchmark clickbench_partitioned.json
   --------------------
   ┏━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓
   ┃ Query        ┃        HEAD ┃  specialize ┃        Change ┃
   ┡━━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩
   │ QQuery 0     │     2.30 ms │     2.63 ms │  1.15x slower │
   │ QQuery 1     │    50.35 ms │    48.86 ms │     no change │
   │ QQuery 2     │   133.49 ms │   136.16 ms │     no change │
   │ QQuery 3     │   161.31 ms │   157.45 ms │     no change │
   │ QQuery 4     │  1050.15 ms │  1063.97 ms │     no change │
   │ QQuery 5     │  1491.70 ms │  1533.79 ms │     no change │
   │ QQuery 6     │     2.32 ms │     2.21 ms │     no change │
   │ QQuery 7     │    53.70 ms │    55.25 ms │     no change │
   │ QQuery 8     │  1408.68 ms │  1416.73 ms │     no change │
   │ QQuery 9     │  1853.09 ms │  1880.40 ms │     no change │
   │ QQuery 10    │   375.13 ms │   375.41 ms │     no change │
   │ QQuery 11    │   424.63 ms │   427.53 ms │     no change │
   │ QQuery 12    │  1346.21 ms │  1362.68 ms │     no change │
   │ QQuery 13    │  2015.24 ms │  2015.19 ms │     no change │
   │ QQuery 14    │  1266.73 ms │  1283.79 ms │     no change │
   │ QQuery 15    │  1245.36 ms │  1231.93 ms │     no change │
   │ QQuery 16    │  2639.03 ms │  2674.74 ms │     no change │
   │ QQuery 17    │  2620.13 ms │  2634.50 ms │     no change │
   │ QQuery 18    │  5216.94 ms │  4964.91 ms │     no change │
   │ QQuery 19    │   124.64 ms │   123.02 ms │     no change │
   │ QQuery 20    │  1918.23 ms │  1925.17 ms │     no change │
   │ QQuery 21    │  2227.98 ms │  2213.04 ms │     no change │
   │ QQuery 22    │  3820.04 ms │  3811.79 ms │     no change │
   │ QQuery 23    │ 12877.19 ms │ 12654.96 ms │     no change │
   │ QQuery 24    │   220.67 ms │   216.55 ms │     no change │
   │ QQuery 25    │   485.06 ms │   484.94 ms │     no change │
   │ QQuery 26    │   228.37 ms │   227.93 ms │     no change │
   │ QQuery 27    │  2788.67 ms │  2762.40 ms │     no change │
   │ QQuery 28    │ 23625.38 ms │ 23351.35 ms │     no change │
   │ QQuery 29    │   969.25 ms │   940.18 ms │     no change │
   │ QQuery 30    │  1319.82 ms │  1324.33 ms │     no change │
   │ QQuery 31    │  1392.71 ms │  1336.34 ms │     no change │
   │ QQuery 32    │  5596.43 ms │  4659.76 ms │ +1.20x faster │
   │ QQuery 33    │  6275.42 ms │  5799.97 ms │ +1.08x faster │
   │ QQuery 34    │  6090.08 ms │  5911.28 ms │     no change │
   │ QQuery 35    │  1911.77 ms │  1891.01 ms │     no change │
   │ QQuery 36    │   116.63 ms │   122.98 ms │  1.05x slower │
   │ QQuery 37    │    56.94 ms │    58.76 ms │     no change │
   │ QQuery 38    │   120.21 ms │   117.10 ms │     no change │
   │ QQuery 39    │   193.14 ms │   195.20 ms │     no change │
   │ QQuery 40    │    46.81 ms │    47.14 ms │     no change │
   │ QQuery 41    │    42.14 ms │    42.96 ms │     no change │
   │ QQuery 42    │    34.63 ms │    36.02 ms │     no change │
   └──────────────┴─────────────┴─────────────┴───────────────┘
   ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━┓
   ┃ Benchmark Summary         ┃            ┃
   ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━┩
   │ Total Time (HEAD)         │ 95838.70ms │
   │ Total Time (specialize)   │ 93522.32ms │
   │ Average Time (HEAD)       │  2228.81ms │
   │ Average Time (specialize) │  2174.94ms │
   │ Queries Faster            │          2 │
   │ Queries Slower            │          2 │
   │ Queries with No Change    │         39 │
   │ Queries with Failure      │          0 │
   └───────────────────────────┴────────────┘
   ```
   
   
   </p>
   </details>
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "alamb-ghbot (via GitHub)" <gi...@apache.org>.
alamb-ghbot commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3634545622

   🤖: Benchmark completed
   
   <details><summary>Details</summary>
   <p>
   
   
   ```
   group                                          main                                   specialize
   -----                                          ----                                   ----------
   in_list/Float32/list=100/nulls=0%              1.01    307.1±8.23µs        ? ?/sec    1.00    302.7±1.87µs        ? ?/sec
   in_list/Float32/list=100/nulls=20%             1.04    391.1±2.13µs        ? ?/sec    1.00    374.4±4.60µs        ? ?/sec
   in_list/Float32/list=3/nulls=0%                1.03     14.6±0.17µs        ? ?/sec    1.00     14.2±0.11µs        ? ?/sec
   in_list/Float32/list=3/nulls=20%               1.00     19.7±0.15µs        ? ?/sec    1.00     19.7±0.13µs        ? ?/sec
   in_list/Float32/list=8/nulls=0%                1.00     29.1±0.36µs        ? ?/sec    1.00     29.2±1.14µs        ? ?/sec
   in_list/Float32/list=8/nulls=20%               1.07     39.4±0.27µs        ? ?/sec    1.00     36.8±0.47µs        ? ?/sec
   in_list/Int32/list=100/nulls=0%                1.00      5.9±0.13µs        ? ?/sec    1.06      6.2±0.04µs        ? ?/sec
   in_list/Int32/list=100/nulls=20%               1.06      8.4±0.08µs        ? ?/sec    1.00      7.9±0.11µs        ? ?/sec
   in_list/Int32/list=3/nulls=0%                  1.00      5.6±0.06µs        ? ?/sec    1.21      6.8±0.04µs        ? ?/sec
   in_list/Int32/list=3/nulls=20%                 1.05      8.7±0.07µs        ? ?/sec    1.00      8.3±0.11µs        ? ?/sec
   in_list/Int32/list=8/nulls=0%                  1.00      6.0±0.04µs        ? ?/sec    1.09      6.5±0.16µs        ? ?/sec
   in_list/Int32/list=8/nulls=20%                 1.04      8.4±0.10µs        ? ?/sec    1.00      8.1±0.04µs        ? ?/sec
   in_list/Utf8/list=100/nulls=0%/str=100         1.00   645.1±11.45µs        ? ?/sec    1.00   645.7±12.49µs        ? ?/sec
   in_list/Utf8/list=100/nulls=0%/str=12          1.00    667.7±6.12µs        ? ?/sec    1.03    685.0±3.93µs        ? ?/sec
   in_list/Utf8/list=100/nulls=0%/str=3           1.00    669.3±4.02µs        ? ?/sec    1.06    707.1±7.55µs        ? ?/sec
   in_list/Utf8/list=100/nulls=20%/str=100        1.00    594.9±3.67µs        ? ?/sec    1.02   604.8±12.27µs        ? ?/sec
   in_list/Utf8/list=100/nulls=20%/str=12         1.00    613.4±6.72µs        ? ?/sec    1.02    627.5±5.92µs        ? ?/sec
   in_list/Utf8/list=100/nulls=20%/str=3          1.00    615.7±2.78µs        ? ?/sec    1.02    627.1±3.23µs        ? ?/sec
   in_list/Utf8/list=3/nulls=0%/str=100           1.01     27.3±0.97µs        ? ?/sec    1.00     27.0±1.15µs        ? ?/sec
   in_list/Utf8/list=3/nulls=0%/str=12            1.06     27.4±0.34µs        ? ?/sec    1.00     25.9±0.40µs        ? ?/sec
   in_list/Utf8/list=3/nulls=0%/str=3             1.00     28.3±1.19µs        ? ?/sec    1.04     29.4±3.04µs        ? ?/sec
   in_list/Utf8/list=3/nulls=20%/str=100          1.02     26.2±0.26µs        ? ?/sec    1.00     25.8±0.51µs        ? ?/sec
   in_list/Utf8/list=3/nulls=20%/str=12           1.00     27.1±0.10µs        ? ?/sec    1.05     28.5±1.12µs        ? ?/sec
   in_list/Utf8/list=3/nulls=20%/str=3            1.04     27.7±0.75µs        ? ?/sec    1.00     26.5±0.55µs        ? ?/sec
   in_list/Utf8/list=8/nulls=0%/str=100           1.00     56.7±1.89µs        ? ?/sec    1.00     56.4±0.99µs        ? ?/sec
   in_list/Utf8/list=8/nulls=0%/str=12            1.00     57.8±2.60µs        ? ?/sec    1.02     59.2±0.56µs        ? ?/sec
   in_list/Utf8/list=8/nulls=0%/str=3             1.00     58.7±0.24µs        ? ?/sec    1.09     64.3±6.59µs        ? ?/sec
   in_list/Utf8/list=8/nulls=20%/str=100          1.03     53.4±1.32µs        ? ?/sec    1.00     51.9±0.10µs        ? ?/sec
   in_list/Utf8/list=8/nulls=20%/str=12           1.00     54.2±1.31µs        ? ?/sec    1.00     54.5±0.69µs        ? ?/sec
   in_list/Utf8/list=8/nulls=20%/str=3            1.01     54.6±0.20µs        ? ?/sec    1.00     53.8±0.53µs        ? ?/sec
   in_list/Utf8View/list=100/nulls=0%/str=100     1.00    597.3±9.22µs        ? ?/sec    1.01   603.2±10.62µs        ? ?/sec
   in_list/Utf8View/list=100/nulls=0%/str=12      1.00   581.4±24.63µs        ? ?/sec    1.00   581.1±13.15µs        ? ?/sec
   in_list/Utf8View/list=100/nulls=0%/str=3       1.01   582.3±12.05µs        ? ?/sec    1.00    578.6±5.55µs        ? ?/sec
   in_list/Utf8View/list=100/nulls=20%/str=100    1.00    503.3±5.49µs        ? ?/sec    1.02   515.1±27.03µs        ? ?/sec
   in_list/Utf8View/list=100/nulls=20%/str=12     1.00    510.9±6.95µs        ? ?/sec    1.01    515.3±6.38µs        ? ?/sec
   in_list/Utf8View/list=100/nulls=20%/str=3      1.00    515.1±7.18µs        ? ?/sec    1.01   522.1±13.63µs        ? ?/sec
   in_list/Utf8View/list=3/nulls=0%/str=100       1.05     22.2±0.28µs        ? ?/sec    1.00     21.1±0.24µs        ? ?/sec
   in_list/Utf8View/list=3/nulls=0%/str=12        1.05     23.3±0.62µs        ? ?/sec    1.00     22.3±0.30µs        ? ?/sec
   in_list/Utf8View/list=3/nulls=0%/str=3         1.04     23.3±0.18µs        ? ?/sec    1.00     22.4±0.82µs        ? ?/sec
   in_list/Utf8View/list=3/nulls=20%/str=100      1.00     22.8±0.22µs        ? ?/sec    1.02     23.2±0.24µs        ? ?/sec
   in_list/Utf8View/list=3/nulls=20%/str=12       1.00     23.4±0.18µs        ? ?/sec    1.03     24.2±0.49µs        ? ?/sec
   in_list/Utf8View/list=3/nulls=20%/str=3        1.00     23.7±0.37µs        ? ?/sec    1.02     24.2±1.51µs        ? ?/sec
   in_list/Utf8View/list=8/nulls=0%/str=100       1.05     49.6±3.83µs        ? ?/sec    1.00     47.2±0.83µs        ? ?/sec
   in_list/Utf8View/list=8/nulls=0%/str=12        1.00     50.5±0.65µs        ? ?/sec    1.18     59.7±1.62µs        ? ?/sec
   in_list/Utf8View/list=8/nulls=0%/str=3         1.00     50.6±0.72µs        ? ?/sec    1.17     59.5±0.70µs        ? ?/sec
   in_list/Utf8View/list=8/nulls=20%/str=100      1.00     45.4±2.06µs        ? ?/sec    1.06     48.2±1.59µs        ? ?/sec
   in_list/Utf8View/list=8/nulls=20%/str=12       1.01     47.3±0.67µs        ? ?/sec    1.00     46.8±0.83µs        ? ?/sec
   in_list/Utf8View/list=8/nulls=20%/str=3        1.01     49.1±0.36µs        ? ?/sec    1.00     48.6±1.29µs        ? ?/sec
   ```
   
   
   </p>
   </details>
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "Dandandan (via GitHub)" <gi...@apache.org>.
Dandandan commented on code in PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#discussion_r2601222932


##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,65 +248,414 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
-    null_count: usize,
-    values: HashSet<i32>,
+/// Threshold for switching from sorted Vec (binary search) to HashSet
+/// For small lists, binary search has better cache locality and lower overhead
+/// Maximum list size for using sorted lookup (binary search).
+/// Lists with more elements use hash lookup instead.
+const SORTED_LOOKUP_MAX_LEN: usize = 8;
+
+/// Helper to build a BooleanArray result for IN list operations.
+/// Handles SQL three-valued logic for NULL values.
+///
+/// # Arguments
+/// * `len` - Number of elements in the needle array
+/// * `needle_nulls` - Optional validity buffer from the needle array
+/// * `haystack_has_nulls` - Whether the IN list contains NULL values
+/// * `negated` - Whether this is a NOT IN operation
+/// * `contains` - Closure that returns whether needle[i] is found in the haystack
+#[inline]
+fn build_in_list_result<C>(
+    len: usize,
+    needle_nulls: Option<&NullBuffer>,
+    haystack_has_nulls: bool,
+    negated: bool,
+    contains: C,
+) -> BooleanArray
+where
+    C: Fn(usize) -> bool,
+{
+    // Use collect_bool for all paths - it's vectorized and faster than element-by-element append.
+    // Match on (needle_has_nulls, haystack_has_nulls, negated) to specialize each case.
+    match (needle_nulls, haystack_has_nulls, negated) {
+        // Haystack has nulls: result is NULL when not found (might match the NULL)
+        // values_buf == nulls_buf, so compute once and clone
+        (Some(validity), true, false) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let buf = validity.inner() & &contains_buf;
+            BooleanArray::new(buf.clone(), Some(NullBuffer::new(buf)))
+        }
+        (None, true, false) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            BooleanArray::new(buf.clone(), Some(NullBuffer::new(buf)))
+        }
+        (Some(validity), true, true) => {
+            // Compute nulls_buf via SIMD AND, then derive values_buf via XOR.
+            // Uses identity: A & !B = A ^ (A & B) to get values from nulls.
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let nulls_buf = validity.inner() & &contains_buf;
+            let values_buf = validity.inner() ^ &nulls_buf; // valid & !contains
+            BooleanArray::new(values_buf, Some(NullBuffer::new(nulls_buf)))
+        }
+        (None, true, true) => {
+            // No needle nulls, but haystack has nulls
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = !&contains_buf;
+            BooleanArray::new(values_buf, Some(NullBuffer::new(contains_buf)))
+        }
+        // Only needle has nulls: nulls_buf is just validity (reuse it directly!)
+        (Some(validity), false, false) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = validity.inner() & &contains_buf;
+            BooleanArray::new(values_buf, Some(validity.clone()))
+        }
+        (Some(validity), false, true) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = validity.inner() & &(!&contains_buf);
+            BooleanArray::new(values_buf, Some(validity.clone()))
+        }
+        // No nulls anywhere: no validity buffer needed
+        (None, false, false) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            BooleanArray::new(buf, None)
+        }
+        (None, false, true) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| !contains(i));
+            BooleanArray::new(buf, None)
+        }
+    }
 }
 
-impl Int32StaticFilter {
-    fn try_new(in_array: &ArrayRef) -> Result<Self> {
-        let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+/// Sorted lookup using binary search. Best for small lists (< 8 elements).
+struct SortedLookup<T>(Vec<T>);
 
-        let mut values = HashSet::with_capacity(in_array.len());
-        let null_count = in_array.null_count();
+impl<T: Ord> SortedLookup<T> {
+    fn new(mut values: Vec<T>) -> Self {
+        values.sort_unstable();
+        values.dedup();
+        Self(values)
+    }
 
-        for v in in_array.iter().flatten() {
-            values.insert(v);
-        }
+    #[inline]
+    fn contains(&self, value: &T) -> bool {
+        self.0.binary_search(value).is_ok()

Review Comment:
   How does a linear search (`slice::contains`) compare against binary search? I would assume for small lists this can be slightly faster than binary search?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#discussion_r2552997998


##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -1028,6 +1104,612 @@ mod tests {
         Ok(())
     }
 
+    #[test]
+    fn in_list_int8() -> Result<()> {

Review Comment:
   Can we please reduce the duplication in tests here? It seems like we there are like 16 copies of the same test
   
   Reducing the duplication will make it easier to understand what is being covered



##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,68 +211,127 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
-    null_count: usize,
-    values: HashSet<i32>,
-}
+// Macro to generate specialized StaticFilter implementations for primitive types
+macro_rules! primitive_static_filter {
+    ($Name:ident, $ArrowType:ty) => {
+        struct $Name {
+            null_count: usize,
+            values: HashSet<<$ArrowType as ArrowPrimitiveType>::Native>,
+        }
 
-impl Int32StaticFilter {
-    fn try_new(in_array: &ArrayRef) -> Result<Self> {
-        let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+        impl $Name {
+            fn try_new(in_array: &ArrayRef) -> Result<Self> {
+                let in_array = in_array
+                    .as_primitive_opt::<$ArrowType>()
+                    .ok_or_else(|| exec_datafusion_err!("Failed to downcast an array to a '{}' array", stringify!($ArrowType)))?;
 
-        let mut values = HashSet::with_capacity(in_array.len());
-        let null_count = in_array.null_count();
+                let mut values = HashSet::with_capacity(in_array.len());
+                let null_count = in_array.null_count();
+
+                for v in in_array.iter().flatten() {
+                    values.insert(v);
+                }
 
-        for v in in_array.iter().flatten() {
-            values.insert(v);
+                Ok(Self { null_count, values })
+            }
         }
 
-        Ok(Self { null_count, values })
-    }
-}
+        impl StaticFilter for $Name {
+            fn null_count(&self) -> usize {
+                self.null_count
+            }
 
-impl StaticFilter for Int32StaticFilter {
-    fn null_count(&self) -> usize {
-        self.null_count
-    }
+            fn contains(&self, v: &dyn Array, negated: bool) -> Result<BooleanArray> {
+                // Handle dictionary arrays by recursing on the values
+                downcast_dictionary_array! {

Review Comment:
   I didn't see any tests for dictionaries 🤔 



##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,68 +211,127 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
-    null_count: usize,
-    values: HashSet<i32>,
-}
+// Macro to generate specialized StaticFilter implementations for primitive types
+macro_rules! primitive_static_filter {
+    ($Name:ident, $ArrowType:ty) => {
+        struct $Name {
+            null_count: usize,
+            values: HashSet<<$ArrowType as ArrowPrimitiveType>::Native>,
+        }
 
-impl Int32StaticFilter {
-    fn try_new(in_array: &ArrayRef) -> Result<Self> {
-        let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+        impl $Name {
+            fn try_new(in_array: &ArrayRef) -> Result<Self> {
+                let in_array = in_array
+                    .as_primitive_opt::<$ArrowType>()
+                    .ok_or_else(|| exec_datafusion_err!("Failed to downcast an array to a '{}' array", stringify!($ArrowType)))?;
 
-        let mut values = HashSet::with_capacity(in_array.len());
-        let null_count = in_array.null_count();
+                let mut values = HashSet::with_capacity(in_array.len());
+                let null_count = in_array.null_count();
+
+                for v in in_array.iter().flatten() {
+                    values.insert(v);
+                }
 
-        for v in in_array.iter().flatten() {
-            values.insert(v);
+                Ok(Self { null_count, values })
+            }
         }
 
-        Ok(Self { null_count, values })
-    }
-}
+        impl StaticFilter for $Name {
+            fn null_count(&self) -> usize {
+                self.null_count
+            }
 
-impl StaticFilter for Int32StaticFilter {
-    fn null_count(&self) -> usize {
-        self.null_count
-    }
+            fn contains(&self, v: &dyn Array, negated: bool) -> Result<BooleanArray> {
+                // Handle dictionary arrays by recursing on the values
+                downcast_dictionary_array! {
+                    v => {
+                        let values_contains = self.contains(v.values().as_ref(), negated)?;
+                        let result = take(&values_contains, v.keys(), None)?;
+                        return Ok(downcast_array(result.as_ref()))
+                    }
+                    _ => {}
+                }
 
-    fn contains(&self, v: &dyn Array, negated: bool) -> Result<BooleanArray> {
-        let v = v
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
-
-        let result = match (v.null_count() > 0, negated) {
-            (true, false) => {
-                // has nulls, not negated"
-                BooleanArray::from_iter(
-                    v.iter().map(|value| Some(self.values.contains(&value?))),
-                )
-            }
-            (true, true) => {
-                // has nulls, negated
-                BooleanArray::from_iter(
-                    v.iter().map(|value| Some(!self.values.contains(&value?))),
-                )
-            }
-            (false, false) => {
-                //no null, not negated
-                BooleanArray::from_iter(
-                    v.values().iter().map(|value| self.values.contains(value)),
-                )
-            }
-            (false, true) => {
-                // no null, negated
-                BooleanArray::from_iter(
-                    v.values().iter().map(|value| !self.values.contains(value)),
-                )
+                let v = v
+                    .as_primitive_opt::<$ArrowType>()
+                    .ok_or_else(|| exec_datafusion_err!("Failed to downcast an array to a '{}' array", stringify!($ArrowType)))?;
+
+                let haystack_has_nulls = self.null_count > 0;
+
+                let result = match (v.null_count() > 0, haystack_has_nulls, negated) {
+                    (true, _, false) | (false, true, false) => {
+                        // Either needle or haystack has nulls, not negated
+                        BooleanArray::from_iter(v.iter().map(|value| {
+                            match value {
+                                // SQL three-valued logic: null IN (...) is always null
+                                None => None,
+                                Some(v) => {
+                                    if self.values.contains(&v) {
+                                        Some(true)
+                                    } else if haystack_has_nulls {
+                                        // value not in set, but set has nulls -> null
+                                        None
+                                    } else {
+                                        Some(false)
+                                    }
+                                }
+                            }
+                        }))
+                    }
+                    (true, _, true) | (false, true, true) => {
+                        // Either needle or haystack has nulls, negated
+                        BooleanArray::from_iter(v.iter().map(|value| {
+                            match value {
+                                // SQL three-valued logic: null NOT IN (...) is always null
+                                None => None,
+                                Some(v) => {
+                                    if self.values.contains(&v) {
+                                        Some(false)
+                                    } else if haystack_has_nulls {
+                                        // value not in set, but set has nulls -> null
+                                        None
+                                    } else {
+                                        Some(true)
+                                    }
+                                }
+                            }
+                        }))
+                    }
+                    (false, false, false) => {
+                        // no nulls anywhere, not negated
+                        let values = v.values();
+                        let mut builder = BooleanBufferBuilder::new(values.len());
+                        for value in values.iter() {
+                            builder.append(self.values.contains(value));
+                        }
+                        BooleanArray::new(builder.finish(), None)
+                    }
+                    (false, false, true) => {
+                        let values = v.values();

Review Comment:
   This code appears to be uncovered by tests. I tested using
   
   ```rust
   cargo llvm-cov test --html -p datafusion-physical-expr --lib -- in_lis
   ```
   
   
   <img width="965" height="335" alt="Image" src="https://github.com/user-attachments/assets/3e8694cb-e727-47d7-929b-8f7703dcfe06" />
   
   
   
   Here is the whole report in case that is useful [llvm-cov.zip](https://github.com/user-attachments/files/23688528/llvm-cov.zip)



##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -1028,6 +1104,612 @@ mod tests {
         Ok(())
     }
 
+    #[test]
+    fn in_list_int8() -> Result<()> {
+        let schema = Schema::new(vec![Field::new("a", DataType::Int8, true)]);
+        let a = Int8Array::from(vec![Some(0), Some(2), None]);
+        let col_a = col("a", &schema)?;
+        let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
+
+        // expression: "a in (0, 1)"
+        let list = vec![lit(0i8), lit(1i8)];
+        in_list!(
+            batch,
+            list,
+            &false,
+            vec![Some(true), Some(false), None],
+            Arc::clone(&col_a),
+            &schema
+        );
+
+        // expression: "a not in (0, 1)"
+        let list = vec![lit(0i8), lit(1i8)];
+        in_list!(
+            batch,
+            list,
+            &true,
+            vec![Some(false), Some(true), None],
+            Arc::clone(&col_a),
+            &schema
+        );
+
+        // expression: "a in (0, 1, NULL)"
+        let list = vec![lit(0i8), lit(1i8), lit(ScalarValue::Null)];
+        in_list!(
+            batch,
+            list,
+            &false,
+            vec![Some(true), None, None],
+            Arc::clone(&col_a),
+            &schema
+        );
+
+        // expression: "a not in (0, 1, NULL)"
+        let list = vec![lit(0i8), lit(1i8), lit(ScalarValue::Null)];
+        in_list!(
+            batch,
+            list,
+            &true,
+            vec![Some(false), None, None],
+            Arc::clone(&col_a),
+            &schema
+        );
+
+        Ok(())
+    }
+
+    #[test]
+    fn in_list_int16() -> Result<()> {
+        let schema = Schema::new(vec![Field::new("a", DataType::Int16, true)]);
+        let a = Int16Array::from(vec![Some(0), Some(2), None]);
+        let col_a = col("a", &schema)?;
+        let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
+
+        // expression: "a in (0, 1)"
+        let list = vec![lit(0i16), lit(1i16)];
+        in_list!(
+            batch,
+            list,
+            &false,
+            vec![Some(true), Some(false), None],
+            Arc::clone(&col_a),
+            &schema
+        );
+
+        // expression: "a not in (0, 1)"
+        let list = vec![lit(0i16), lit(1i16)];
+        in_list!(
+            batch,
+            list,
+            &true,
+            vec![Some(false), Some(true), None],
+            Arc::clone(&col_a),
+            &schema
+        );
+
+        // expression: "a in (0, 1, NULL)"
+        let list = vec![lit(0i16), lit(1i16), lit(ScalarValue::Null)];
+        in_list!(
+            batch,
+            list,
+            &false,
+            vec![Some(true), None, None],
+            Arc::clone(&col_a),
+            &schema
+        );
+
+        // expression: "a not in (0, 1, NULL)"
+        let list = vec![lit(0i16), lit(1i16), lit(ScalarValue::Null)];
+        in_list!(
+            batch,
+            list,
+            &true,
+            vec![Some(false), None, None],
+            Arc::clone(&col_a),
+            &schema
+        );
+
+        Ok(())
+    }
+
+    #[test]
+    fn in_list_int32() -> Result<()> {
+        let schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]);
+        let a = Int32Array::from(vec![Some(0), Some(2), None]);
+        let col_a = col("a", &schema)?;
+        let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
+
+        // expression: "a in (0, 1)"
+        let list = vec![lit(0i32), lit(1i32)];
+        in_list!(
+            batch,
+            list,
+            &false,
+            vec![Some(true), Some(false), None],
+            Arc::clone(&col_a),
+            &schema
+        );
+
+        // expression: "a not in (0, 1)"
+        let list = vec![lit(0i32), lit(1i32)];
+        in_list!(
+            batch,
+            list,
+            &true,
+            vec![Some(false), Some(true), None],
+            Arc::clone(&col_a),
+            &schema
+        );
+
+        // expression: "a in (0, 1, NULL)"
+        let list = vec![lit(0i32), lit(1i32), lit(ScalarValue::Null)];
+        in_list!(
+            batch,
+            list,
+            &false,
+            vec![Some(true), None, None],
+            Arc::clone(&col_a),
+            &schema
+        );
+
+        // expression: "a not in (0, 1, NULL)"
+        let list = vec![lit(0i32), lit(1i32), lit(ScalarValue::Null)];
+        in_list!(
+            batch,
+            list,
+            &true,
+            vec![Some(false), None, None],
+            Arc::clone(&col_a),
+            &schema
+        );
+
+        Ok(())
+    }
+
+    #[test]
+    fn in_list_uint8() -> Result<()> {
+        let schema = Schema::new(vec![Field::new("a", DataType::UInt8, true)]);
+        let a = UInt8Array::from(vec![Some(0), Some(2), None]);
+        let col_a = col("a", &schema)?;
+        let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
+
+        // expression: "a in (0, 1)"
+        let list = vec![lit(0u8), lit(1u8)];
+        in_list!(
+            batch,
+            list,
+            &false,
+            vec![Some(true), Some(false), None],
+            Arc::clone(&col_a),
+            &schema
+        );
+
+        // expression: "a not in (0, 1)"
+        let list = vec![lit(0u8), lit(1u8)];
+        in_list!(
+            batch,
+            list,
+            &true,
+            vec![Some(false), Some(true), None],
+            Arc::clone(&col_a),
+            &schema
+        );
+
+        // expression: "a in (0, 1, NULL)"
+        let list = vec![lit(0u8), lit(1u8), lit(ScalarValue::Null)];
+        in_list!(
+            batch,
+            list,
+            &false,
+            vec![Some(true), None, None],
+            Arc::clone(&col_a),
+            &schema
+        );
+
+        // expression: "a not in (0, 1, NULL)"
+        let list = vec![lit(0u8), lit(1u8), lit(ScalarValue::Null)];
+        in_list!(
+            batch,
+            list,
+            &true,
+            vec![Some(false), None, None],
+            Arc::clone(&col_a),
+            &schema
+        );
+
+        Ok(())
+    }
+
+    #[test]
+    fn in_list_uint16() -> Result<()> {
+        let schema = Schema::new(vec![Field::new("a", DataType::UInt16, true)]);
+        let a = UInt16Array::from(vec![Some(0), Some(2), None]);
+        let col_a = col("a", &schema)?;
+        let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
+
+        // expression: "a in (0, 1)"
+        let list = vec![lit(0u16), lit(1u16)];
+        in_list!(
+            batch,
+            list,
+            &false,
+            vec![Some(true), Some(false), None],
+            Arc::clone(&col_a),
+            &schema
+        );
+
+        // expression: "a not in (0, 1)"
+        let list = vec![lit(0u16), lit(1u16)];
+        in_list!(
+            batch,
+            list,
+            &true,
+            vec![Some(false), Some(true), None],
+            Arc::clone(&col_a),
+            &schema
+        );
+
+        // expression: "a in (0, 1, NULL)"
+        let list = vec![lit(0u16), lit(1u16), lit(ScalarValue::Null)];
+        in_list!(
+            batch,
+            list,
+            &false,
+            vec![Some(true), None, None],
+            Arc::clone(&col_a),
+            &schema
+        );
+
+        // expression: "a not in (0, 1, NULL)"
+        let list = vec![lit(0u16), lit(1u16), lit(ScalarValue::Null)];
+        in_list!(
+            batch,
+            list,
+            &true,
+            vec![Some(false), None, None],
+            Arc::clone(&col_a),
+            &schema
+        );
+
+        Ok(())
+    }
+
+    #[test]
+    fn in_list_uint32() -> Result<()> {
+        let schema = Schema::new(vec![Field::new("a", DataType::UInt32, true)]);
+        let a = UInt32Array::from(vec![Some(0), Some(2), None]);
+        let col_a = col("a", &schema)?;
+        let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
+
+        // expression: "a in (0, 1)"
+        let list = vec![lit(0u32), lit(1u32)];
+        in_list!(
+            batch,
+            list,
+            &false,
+            vec![Some(true), Some(false), None],
+            Arc::clone(&col_a),
+            &schema
+        );
+
+        // expression: "a not in (0, 1)"
+        let list = vec![lit(0u32), lit(1u32)];
+        in_list!(
+            batch,
+            list,
+            &true,
+            vec![Some(false), Some(true), None],
+            Arc::clone(&col_a),
+            &schema
+        );
+
+        // expression: "a in (0, 1, NULL)"
+        let list = vec![lit(0u32), lit(1u32), lit(ScalarValue::Null)];
+        in_list!(
+            batch,
+            list,
+            &false,
+            vec![Some(true), None, None],
+            Arc::clone(&col_a),
+            &schema
+        );
+
+        // expression: "a not in (0, 1, NULL)"
+        let list = vec![lit(0u32), lit(1u32), lit(ScalarValue::Null)];
+        in_list!(
+            batch,
+            list,
+            &true,
+            vec![Some(false), None, None],
+            Arc::clone(&col_a),
+            &schema
+        );
+
+        Ok(())
+    }
+
+    #[test]
+    fn in_list_uint64() -> Result<()> {
+        let schema = Schema::new(vec![Field::new("a", DataType::UInt64, true)]);
+        let a = UInt64Array::from(vec![Some(0), Some(2), None]);
+        let col_a = col("a", &schema)?;
+        let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
+
+        // expression: "a in (0, 1)"
+        let list = vec![lit(0u64), lit(1u64)];
+        in_list!(
+            batch,
+            list,
+            &false,
+            vec![Some(true), Some(false), None],
+            Arc::clone(&col_a),
+            &schema
+        );
+
+        // expression: "a not in (0, 1)"
+        let list = vec![lit(0u64), lit(1u64)];
+        in_list!(
+            batch,
+            list,
+            &true,
+            vec![Some(false), Some(true), None],
+            Arc::clone(&col_a),
+            &schema
+        );
+
+        // expression: "a in (0, 1, NULL)"
+        let list = vec![lit(0u64), lit(1u64), lit(ScalarValue::Null)];
+        in_list!(
+            batch,
+            list,
+            &false,
+            vec![Some(true), None, None],
+            Arc::clone(&col_a),
+            &schema
+        );
+
+        // expression: "a not in (0, 1, NULL)"
+        let list = vec![lit(0u64), lit(1u64), lit(ScalarValue::Null)];
+        in_list!(
+            batch,
+            list,
+            &true,
+            vec![Some(false), None, None],
+            Arc::clone(&col_a),
+            &schema
+        );
+
+        Ok(())
+    }
+
+    #[test]
+    fn in_list_large_utf8() -> Result<()> {
+        let schema = Schema::new(vec![Field::new("a", DataType::LargeUtf8, true)]);
+        let a = LargeStringArray::from(vec![Some("a"), Some("d"), None]);
+        let col_a = col("a", &schema)?;
+        let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
+
+        // expression: "a in ("a", "b")"
+        let list = vec![lit("a"), lit("b")];
+        in_list!(
+            batch,
+            list,
+            &false,
+            vec![Some(true), Some(false), None],
+            Arc::clone(&col_a),
+            &schema
+        );
+
+        // expression: "a not in ("a", "b")"
+        let list = vec![lit("a"), lit("b")];
+        in_list!(
+            batch,
+            list,
+            &true,
+            vec![Some(false), Some(true), None],
+            Arc::clone(&col_a),
+            &schema
+        );
+
+        // expression: "a in ("a", "b", null)"
+        let list = vec![lit("a"), lit("b"), lit(ScalarValue::LargeUtf8(None))];
+        in_list!(
+            batch,
+            list,
+            &false,
+            vec![Some(true), None, None],
+            Arc::clone(&col_a),
+            &schema
+        );
+
+        // expression: "a not in ("a", "b", null)"
+        let list = vec![lit("a"), lit("b"), lit(ScalarValue::LargeUtf8(None))];
+        in_list!(
+            batch,
+            list,
+            &true,
+            vec![Some(false), None, None],
+            Arc::clone(&col_a),
+            &schema
+        );
+
+        Ok(())
+    }
+
+    #[test]
+    fn in_list_utf8_view() -> Result<()> {

Review Comment:
   this PR has tests for utf8 but no changes for those types. Is that your intention?



##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,68 +206,122 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
-    null_count: usize,
-    values: HashSet<i32>,
-}
+// Macro to generate specialized StaticFilter implementations for primitive types
+macro_rules! primitive_static_filter {
+    ($Name:ident, $ArrowType:ty) => {
+        struct $Name {
+            null_count: usize,
+            values: HashSet<<$ArrowType as ArrowPrimitiveType>::Native>,
+        }
 
-impl Int32StaticFilter {
-    fn try_new(in_array: &ArrayRef) -> Result<Self> {
-        let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+        impl $Name {
+            fn try_new(in_array: &ArrayRef) -> Result<Self> {
+                let in_array = in_array
+                    .as_primitive_opt::<$ArrowType>()
+                    .ok_or_else(|| exec_datafusion_err!(format!("Failed to downcast an array to a '{}' array", stringify!($ArrowType))))?;
 
-        let mut values = HashSet::with_capacity(in_array.len());
-        let null_count = in_array.null_count();
+                let mut values = HashSet::with_capacity(in_array.len());
+                let null_count = in_array.null_count();
+
+                for v in in_array.iter().flatten() {
+                    values.insert(v);
+                }
 
-        for v in in_array.iter().flatten() {
-            values.insert(v);
+                Ok(Self { null_count, values })
+            }
         }
 
-        Ok(Self { null_count, values })
-    }
-}
+        impl StaticFilter for $Name {
+            fn null_count(&self) -> usize {
+                self.null_count
+            }
 
-impl StaticFilter for Int32StaticFilter {
-    fn null_count(&self) -> usize {
-        self.null_count
-    }
+            fn contains(&self, v: &dyn Array, negated: bool) -> Result<BooleanArray> {
+                // Handle dictionary arrays by recursing on the values
+                downcast_dictionary_array! {
+                    v => {
+                        let values_contains = self.contains(v.values().as_ref(), negated)?;
+                        let result = take(&values_contains, v.keys(), None)?;
+                        return Ok(downcast_array(result.as_ref()))
+                    }
+                    _ => {}
+                }
 
-    fn contains(&self, v: &dyn Array, negated: bool) -> Result<BooleanArray> {
-        let v = v
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
-
-        let result = match (v.null_count() > 0, negated) {
-            (true, false) => {
-                // has nulls, not negated"
-                BooleanArray::from_iter(
-                    v.iter().map(|value| Some(self.values.contains(&value?))),
-                )
-            }
-            (true, true) => {
-                // has nulls, negated
-                BooleanArray::from_iter(
-                    v.iter().map(|value| Some(!self.values.contains(&value?))),
-                )
-            }
-            (false, false) => {
-                //no null, not negated
-                BooleanArray::from_iter(
-                    v.values().iter().map(|value| self.values.contains(value)),
-                )
-            }
-            (false, true) => {
-                // no null, negated
-                BooleanArray::from_iter(
-                    v.values().iter().map(|value| !self.values.contains(value)),
-                )
+                let v = v
+                    .as_primitive_opt::<$ArrowType>()
+                    .ok_or_else(|| exec_datafusion_err!(format!("Failed to downcast an array to a '{}' array", stringify!($ArrowType))))?;
+
+                let haystack_has_nulls = self.null_count > 0;
+
+                let result = match (v.null_count() > 0, haystack_has_nulls, negated) {
+                    (true, _, false) | (false, true, false) => {
+                        // Either needle or haystack has nulls, not negated
+                        BooleanArray::from_iter(v.iter().map(|value| {
+                            match value {
+                                // SQL three-valued logic: null IN (...) is always null
+                                None => None,
+                                Some(v) => {
+                                    if self.values.contains(&v) {
+                                        Some(true)
+                                    } else if haystack_has_nulls {
+                                        // value not in set, but set has nulls -> null
+                                        None
+                                    } else {
+                                        Some(false)
+                                    }
+                                }
+                            }
+                        }))
+                    }
+                    (true, _, true) | (false, true, true) => {
+                        // Either needle or haystack has nulls, negated
+                        BooleanArray::from_iter(v.iter().map(|value| {
+                            match value {
+                                // SQL three-valued logic: null NOT IN (...) is always null
+                                None => None,
+                                Some(v) => {
+                                    if self.values.contains(&v) {
+                                        Some(false)
+                                    } else if haystack_has_nulls {
+                                        // value not in set, but set has nulls -> null
+                                        None
+                                    } else {
+                                        Some(true)
+                                    }
+                                }
+                            }
+                        }))
+                    }
+                    (false, false, false) => {
+                        // no nulls anywhere, not negated
+                        BooleanArray::from_iter(

Review Comment:
   We have been discussing various improvements:
   - https://github.com/apache/arrow-rs/issues/8561
   - https://github.com/apache/arrow-rs/issues/8806



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3637945129

   run benchmark in_list


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#discussion_r2603681481


##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,65 +248,414 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
-    null_count: usize,
-    values: HashSet<i32>,
+/// Threshold for switching from sorted Vec (binary search) to HashSet
+/// For small lists, binary search has better cache locality and lower overhead
+/// Maximum list size for using sorted lookup (binary search).
+/// Lists with more elements use hash lookup instead.
+const SORTED_LOOKUP_MAX_LEN: usize = 8;
+
+/// Helper to build a BooleanArray result for IN list operations.
+/// Handles SQL three-valued logic for NULL values.
+///
+/// # Arguments
+/// * `len` - Number of elements in the needle array
+/// * `needle_nulls` - Optional validity buffer from the needle array
+/// * `haystack_has_nulls` - Whether the IN list contains NULL values
+/// * `negated` - Whether this is a NOT IN operation
+/// * `contains` - Closure that returns whether needle[i] is found in the haystack
+#[inline]
+fn build_in_list_result<C>(
+    len: usize,
+    needle_nulls: Option<&NullBuffer>,
+    haystack_has_nulls: bool,
+    negated: bool,
+    contains: C,
+) -> BooleanArray
+where
+    C: Fn(usize) -> bool,
+{
+    // Use collect_bool for all paths - it's vectorized and faster than element-by-element append.
+    // Match on (needle_has_nulls, haystack_has_nulls, negated) to specialize each case.
+    match (needle_nulls, haystack_has_nulls, negated) {
+        // Haystack has nulls: result is NULL when not found (might match the NULL)
+        // values_buf == nulls_buf, so compute once and clone
+        (Some(validity), true, false) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let buf = validity.inner() & &contains_buf;
+            BooleanArray::new(buf.clone(), Some(NullBuffer::new(buf)))
+        }
+        (None, true, false) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            BooleanArray::new(buf.clone(), Some(NullBuffer::new(buf)))
+        }
+        (Some(validity), true, true) => {
+            // Compute nulls_buf via SIMD AND, then derive values_buf via XOR.
+            // Uses identity: A & !B = A ^ (A & B) to get values from nulls.
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let nulls_buf = validity.inner() & &contains_buf;
+            let values_buf = validity.inner() ^ &nulls_buf; // valid & !contains
+            BooleanArray::new(values_buf, Some(NullBuffer::new(nulls_buf)))
+        }
+        (None, true, true) => {
+            // No needle nulls, but haystack has nulls
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = !&contains_buf;
+            BooleanArray::new(values_buf, Some(NullBuffer::new(contains_buf)))
+        }
+        // Only needle has nulls: nulls_buf is just validity (reuse it directly!)
+        (Some(validity), false, false) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = validity.inner() & &contains_buf;
+            BooleanArray::new(values_buf, Some(validity.clone()))
+        }
+        (Some(validity), false, true) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = validity.inner() & &(!&contains_buf);
+            BooleanArray::new(values_buf, Some(validity.clone()))
+        }
+        // No nulls anywhere: no validity buffer needed
+        (None, false, false) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            BooleanArray::new(buf, None)
+        }
+        (None, false, true) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| !contains(i));
+            BooleanArray::new(buf, None)
+        }
+    }
 }
 
-impl Int32StaticFilter {
-    fn try_new(in_array: &ArrayRef) -> Result<Self> {
-        let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+/// Sorted lookup using binary search. Best for small lists (< 8 elements).
+struct SortedLookup<T>(Vec<T>);
 
-        let mut values = HashSet::with_capacity(in_array.len());
-        let null_count = in_array.null_count();
+impl<T: Ord> SortedLookup<T> {
+    fn new(mut values: Vec<T>) -> Self {
+        values.sort_unstable();
+        values.dedup();
+        Self(values)
+    }
 
-        for v in in_array.iter().flatten() {
-            values.insert(v);
-        }
+    #[inline]
+    fn contains(&self, value: &T) -> bool {
+        self.0.binary_search(value).is_ok()

Review Comment:
   Yes, you should probably just revert my commit



##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,65 +248,414 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
-    null_count: usize,
-    values: HashSet<i32>,
+/// Threshold for switching from sorted Vec (binary search) to HashSet
+/// For small lists, binary search has better cache locality and lower overhead
+/// Maximum list size for using sorted lookup (binary search).
+/// Lists with more elements use hash lookup instead.
+const SORTED_LOOKUP_MAX_LEN: usize = 8;
+
+/// Helper to build a BooleanArray result for IN list operations.
+/// Handles SQL three-valued logic for NULL values.
+///
+/// # Arguments
+/// * `len` - Number of elements in the needle array
+/// * `needle_nulls` - Optional validity buffer from the needle array
+/// * `haystack_has_nulls` - Whether the IN list contains NULL values
+/// * `negated` - Whether this is a NOT IN operation
+/// * `contains` - Closure that returns whether needle[i] is found in the haystack
+#[inline]
+fn build_in_list_result<C>(
+    len: usize,
+    needle_nulls: Option<&NullBuffer>,
+    haystack_has_nulls: bool,
+    negated: bool,
+    contains: C,
+) -> BooleanArray
+where
+    C: Fn(usize) -> bool,
+{
+    // Use collect_bool for all paths - it's vectorized and faster than element-by-element append.
+    // Match on (needle_has_nulls, haystack_has_nulls, negated) to specialize each case.
+    match (needle_nulls, haystack_has_nulls, negated) {
+        // Haystack has nulls: result is NULL when not found (might match the NULL)
+        // values_buf == nulls_buf, so compute once and clone
+        (Some(validity), true, false) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let buf = validity.inner() & &contains_buf;
+            BooleanArray::new(buf.clone(), Some(NullBuffer::new(buf)))
+        }
+        (None, true, false) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            BooleanArray::new(buf.clone(), Some(NullBuffer::new(buf)))
+        }
+        (Some(validity), true, true) => {
+            // Compute nulls_buf via SIMD AND, then derive values_buf via XOR.
+            // Uses identity: A & !B = A ^ (A & B) to get values from nulls.
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let nulls_buf = validity.inner() & &contains_buf;
+            let values_buf = validity.inner() ^ &nulls_buf; // valid & !contains
+            BooleanArray::new(values_buf, Some(NullBuffer::new(nulls_buf)))
+        }
+        (None, true, true) => {
+            // No needle nulls, but haystack has nulls
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = !&contains_buf;
+            BooleanArray::new(values_buf, Some(NullBuffer::new(contains_buf)))
+        }
+        // Only needle has nulls: nulls_buf is just validity (reuse it directly!)
+        (Some(validity), false, false) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = validity.inner() & &contains_buf;
+            BooleanArray::new(values_buf, Some(validity.clone()))
+        }
+        (Some(validity), false, true) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = validity.inner() & &(!&contains_buf);
+            BooleanArray::new(values_buf, Some(validity.clone()))
+        }
+        // No nulls anywhere: no validity buffer needed
+        (None, false, false) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            BooleanArray::new(buf, None)
+        }
+        (None, false, true) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| !contains(i));
+            BooleanArray::new(buf, None)
+        }
+    }
 }
 
-impl Int32StaticFilter {
-    fn try_new(in_array: &ArrayRef) -> Result<Self> {
-        let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+/// Sorted lookup using binary search. Best for small lists (< 8 elements).
+struct SortedLookup<T>(Vec<T>);
 
-        let mut values = HashSet::with_capacity(in_array.len());
-        let null_count = in_array.null_count();
+impl<T: Ord> SortedLookup<T> {
+    fn new(mut values: Vec<T>) -> Self {
+        values.sort_unstable();
+        values.dedup();
+        Self(values)
+    }
 
-        for v in in_array.iter().flatten() {
-            values.insert(v);
-        }
+    #[inline]
+    fn contains(&self, value: &T) -> bool {
+        self.0.binary_search(value).is_ok()

Review Comment:
   Yes, you should probably just revert my commit



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3634468395

   run benchmark in_list


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#discussion_r2603365909


##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,65 +248,414 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
-    null_count: usize,
-    values: HashSet<i32>,
+/// Threshold for switching from sorted Vec (binary search) to HashSet
+/// For small lists, binary search has better cache locality and lower overhead
+/// Maximum list size for using sorted lookup (binary search).
+/// Lists with more elements use hash lookup instead.
+const SORTED_LOOKUP_MAX_LEN: usize = 8;
+
+/// Helper to build a BooleanArray result for IN list operations.
+/// Handles SQL three-valued logic for NULL values.
+///
+/// # Arguments
+/// * `len` - Number of elements in the needle array
+/// * `needle_nulls` - Optional validity buffer from the needle array
+/// * `haystack_has_nulls` - Whether the IN list contains NULL values
+/// * `negated` - Whether this is a NOT IN operation
+/// * `contains` - Closure that returns whether needle[i] is found in the haystack
+#[inline]
+fn build_in_list_result<C>(
+    len: usize,
+    needle_nulls: Option<&NullBuffer>,
+    haystack_has_nulls: bool,
+    negated: bool,
+    contains: C,
+) -> BooleanArray
+where
+    C: Fn(usize) -> bool,
+{
+    // Use collect_bool for all paths - it's vectorized and faster than element-by-element append.
+    // Match on (needle_has_nulls, haystack_has_nulls, negated) to specialize each case.
+    match (needle_nulls, haystack_has_nulls, negated) {
+        // Haystack has nulls: result is NULL when not found (might match the NULL)
+        // values_buf == nulls_buf, so compute once and clone
+        (Some(validity), true, false) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let buf = validity.inner() & &contains_buf;
+            BooleanArray::new(buf.clone(), Some(NullBuffer::new(buf)))
+        }
+        (None, true, false) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            BooleanArray::new(buf.clone(), Some(NullBuffer::new(buf)))
+        }
+        (Some(validity), true, true) => {
+            // Compute nulls_buf via SIMD AND, then derive values_buf via XOR.
+            // Uses identity: A & !B = A ^ (A & B) to get values from nulls.
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let nulls_buf = validity.inner() & &contains_buf;
+            let values_buf = validity.inner() ^ &nulls_buf; // valid & !contains
+            BooleanArray::new(values_buf, Some(NullBuffer::new(nulls_buf)))
+        }
+        (None, true, true) => {
+            // No needle nulls, but haystack has nulls
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = !&contains_buf;
+            BooleanArray::new(values_buf, Some(NullBuffer::new(contains_buf)))
+        }
+        // Only needle has nulls: nulls_buf is just validity (reuse it directly!)
+        (Some(validity), false, false) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = validity.inner() & &contains_buf;
+            BooleanArray::new(values_buf, Some(validity.clone()))
+        }
+        (Some(validity), false, true) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = validity.inner() & &(!&contains_buf);
+            BooleanArray::new(values_buf, Some(validity.clone()))
+        }
+        // No nulls anywhere: no validity buffer needed
+        (None, false, false) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            BooleanArray::new(buf, None)
+        }
+        (None, false, true) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| !contains(i));
+            BooleanArray::new(buf, None)
+        }
+    }
 }
 
-impl Int32StaticFilter {
-    fn try_new(in_array: &ArrayRef) -> Result<Self> {
-        let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+/// Sorted lookup using binary search. Best for small lists (< 8 elements).
+struct SortedLookup<T>(Vec<T>);
 
-        let mut values = HashSet::with_capacity(in_array.len());
-        let null_count = in_array.null_count();
+impl<T: Ord> SortedLookup<T> {
+    fn new(mut values: Vec<T>) -> Self {
+        values.sort_unstable();
+        values.dedup();
+        Self(values)
+    }
 
-        for v in in_array.iter().flatten() {
-            values.insert(v);
-        }
+    #[inline]
+    fn contains(&self, value: &T) -> bool {
+        self.0.binary_search(value).is_ok()

Review Comment:
   @Dandandan and @adriangb: I opened a PR to `pydantic` at https://github.com/pydantic/datafusion/pull/48 as a POC with the bench numbers on my mac.
   
   It shows another ~70% improvement on short in-lists of primitive types, and ~40% on short utf8view in-lists as well.
   
   This is a pretty major refactor, so I'm very much in favor of "freezing" the features of this PR and leaving my further improvement to later!



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "alamb-ghbot (via GitHub)" <gi...@apache.org>.
alamb-ghbot commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3643825381

   🤖: Benchmark completed
   
   <details><summary>Details</summary>
   <p>
   
   
   ```
   Comparing HEAD and specialize
   --------------------
   Benchmark tpch_sf1.json
   --------------------
   ┏━━━━━━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━┓
   ┃ Query        ┃      HEAD ┃ specialize ┃    Change ┃
   ┡━━━━━━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━━┩
   │ QQuery 1     │ 224.07 ms │  221.82 ms │ no change │
   │ QQuery 2     │  93.52 ms │   97.12 ms │ no change │
   │ QQuery 3     │ 122.81 ms │  125.01 ms │ no change │
   │ QQuery 4     │  76.70 ms │   76.89 ms │ no change │
   │ QQuery 5     │ 172.98 ms │  174.68 ms │ no change │
   │ QQuery 6     │  63.80 ms │   66.75 ms │ no change │
   │ QQuery 7     │ 213.32 ms │  219.23 ms │ no change │
   │ QQuery 8     │ 159.80 ms │  163.94 ms │ no change │
   │ QQuery 9     │ 223.96 ms │  234.12 ms │ no change │
   │ QQuery 10    │ 191.61 ms │  187.97 ms │ no change │
   │ QQuery 11    │  72.75 ms │   73.41 ms │ no change │
   │ QQuery 12    │ 120.40 ms │  119.68 ms │ no change │
   │ QQuery 13    │ 219.24 ms │  211.24 ms │ no change │
   │ QQuery 14    │  93.52 ms │   92.66 ms │ no change │
   │ QQuery 15    │ 120.30 ms │  117.36 ms │ no change │
   │ QQuery 16    │  56.34 ms │   59.14 ms │ no change │
   │ QQuery 17    │ 297.79 ms │  306.88 ms │ no change │
   │ QQuery 18    │ 319.40 ms │  318.16 ms │ no change │
   │ QQuery 19    │ 136.82 ms │  135.55 ms │ no change │
   │ QQuery 20    │ 124.00 ms │  126.51 ms │ no change │
   │ QQuery 21    │ 259.82 ms │  261.47 ms │ no change │
   │ QQuery 22    │  42.01 ms │   42.84 ms │ no change │
   └──────────────┴───────────┴────────────┴───────────┘
   ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━┓
   ┃ Benchmark Summary         ┃           ┃
   ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━┩
   │ Total Time (HEAD)         │ 3404.96ms │
   │ Total Time (specialize)   │ 3432.44ms │
   │ Average Time (HEAD)       │  154.77ms │
   │ Average Time (specialize) │  156.02ms │
   │ Queries Faster            │         0 │
   │ Queries Slower            │         0 │
   │ Queries with No Change    │        22 │
   │ Queries with Failure      │         0 │
   └───────────────────────────┴───────────┘
   ```
   
   
   </p>
   </details>
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3643904431

   Benchmarks look good to me!


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#discussion_r2608194142


##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,99 +213,302 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
-    null_count: usize,
-    values: HashSet<i32>,
+/// Wrapper for f32 that implements Hash and Eq using IEEE 754 total ordering.
+/// This treats NaN values as equal to each other (using total_cmp).
+#[derive(Clone, Copy)]
+struct OrderedFloat32(f32);
+
+impl Hash for OrderedFloat32 {
+    fn hash<H: Hasher>(&self, state: &mut H) {
+        self.0.to_ne_bytes().hash(state);
+    }
 }
 
-impl Int32StaticFilter {
-    fn try_new(in_array: &ArrayRef) -> Result<Self> {
-        let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+impl PartialEq for OrderedFloat32 {
+    fn eq(&self, other: &Self) -> bool {
+        self.0.total_cmp(&other.0).is_eq()

Review Comment:
   Doesn't equality on floats use `to_bits()` elsewhere? This could lead to inconsistencies for edge cases (NaN, +0, -0 for instance.)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on code in PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#discussion_r2608207615


##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,99 +213,302 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
-    null_count: usize,
-    values: HashSet<i32>,
+/// Wrapper for f32 that implements Hash and Eq using IEEE 754 total ordering.
+/// This treats NaN values as equal to each other (using total_cmp).
+#[derive(Clone, Copy)]
+struct OrderedFloat32(f32);
+
+impl Hash for OrderedFloat32 {
+    fn hash<H: Hasher>(&self, state: &mut H) {
+        self.0.to_ne_bytes().hash(state);
+    }
 }
 
-impl Int32StaticFilter {
-    fn try_new(in_array: &ArrayRef) -> Result<Self> {
-        let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+impl PartialEq for OrderedFloat32 {
+    fn eq(&self, other: &Self) -> bool {
+        self.0.total_cmp(&other.0).is_eq()

Review Comment:
   I added tests for all of those and cross references against postgres/duckdb. But I will try `to_bits()`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "Dandandan (via GitHub)" <gi...@apache.org>.
Dandandan commented on code in PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#discussion_r2549501179


##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,68 +206,122 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
-    null_count: usize,
-    values: HashSet<i32>,
-}
+// Macro to generate specialized StaticFilter implementations for primitive types
+macro_rules! primitive_static_filter {
+    ($Name:ident, $ArrowType:ty) => {
+        struct $Name {
+            null_count: usize,
+            values: HashSet<<$ArrowType as ArrowPrimitiveType>::Native>,
+        }
 
-impl Int32StaticFilter {
-    fn try_new(in_array: &ArrayRef) -> Result<Self> {
-        let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+        impl $Name {
+            fn try_new(in_array: &ArrayRef) -> Result<Self> {
+                let in_array = in_array
+                    .as_primitive_opt::<$ArrowType>()
+                    .ok_or_else(|| exec_datafusion_err!(format!("Failed to downcast an array to a '{}' array", stringify!($ArrowType))))?;
 
-        let mut values = HashSet::with_capacity(in_array.len());
-        let null_count = in_array.null_count();
+                let mut values = HashSet::with_capacity(in_array.len());
+                let null_count = in_array.null_count();
+
+                for v in in_array.iter().flatten() {
+                    values.insert(v);
+                }
 
-        for v in in_array.iter().flatten() {
-            values.insert(v);
+                Ok(Self { null_count, values })
+            }
         }
 
-        Ok(Self { null_count, values })
-    }
-}
+        impl StaticFilter for $Name {
+            fn null_count(&self) -> usize {
+                self.null_count
+            }
 
-impl StaticFilter for Int32StaticFilter {
-    fn null_count(&self) -> usize {
-        self.null_count
-    }
+            fn contains(&self, v: &dyn Array, negated: bool) -> Result<BooleanArray> {
+                // Handle dictionary arrays by recursing on the values
+                downcast_dictionary_array! {
+                    v => {
+                        let values_contains = self.contains(v.values().as_ref(), negated)?;
+                        let result = take(&values_contains, v.keys(), None)?;
+                        return Ok(downcast_array(result.as_ref()))
+                    }
+                    _ => {}
+                }
 
-    fn contains(&self, v: &dyn Array, negated: bool) -> Result<BooleanArray> {
-        let v = v
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
-
-        let result = match (v.null_count() > 0, negated) {
-            (true, false) => {
-                // has nulls, not negated"
-                BooleanArray::from_iter(
-                    v.iter().map(|value| Some(self.values.contains(&value?))),
-                )
-            }
-            (true, true) => {
-                // has nulls, negated
-                BooleanArray::from_iter(
-                    v.iter().map(|value| Some(!self.values.contains(&value?))),
-                )
-            }
-            (false, false) => {
-                //no null, not negated
-                BooleanArray::from_iter(
-                    v.values().iter().map(|value| self.values.contains(value)),
-                )
-            }
-            (false, true) => {
-                // no null, negated
-                BooleanArray::from_iter(
-                    v.values().iter().map(|value| !self.values.contains(value)),
-                )
+                let v = v
+                    .as_primitive_opt::<$ArrowType>()
+                    .ok_or_else(|| exec_datafusion_err!(format!("Failed to downcast an array to a '{}' array", stringify!($ArrowType))))?;
+
+                let haystack_has_nulls = self.null_count > 0;
+
+                let result = match (v.null_count() > 0, haystack_has_nulls, negated) {
+                    (true, _, false) | (false, true, false) => {
+                        // Either needle or haystack has nulls, not negated
+                        BooleanArray::from_iter(v.iter().map(|value| {

Review Comment:
   `BooleanArray::collect_bool` is much faster



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "alamb-ghbot (via GitHub)" <gi...@apache.org>.
alamb-ghbot commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3637438285

   🤖 Hi @adriangb, thanks for the request (https://github.com/apache/datafusion/pull/18832#issuecomment-3637437969).
   
   [`scrape_comments.py`](https://github.com/alamb/datafusion-benchmarking/blob/main/scripts/scrape_comments.py) only supports whitelisted benchmarks.
   - Standard: clickbench_1, clickbench_extended, clickbench_partitioned, clickbench_pushdown, tpch, tpch10, tpch_mem, tpch_mem10
   - Criterion: aggregate_query_sql, aggregate_vectorized, case_when, in_list, sql_planner
   
   Please choose one or more of these with `run benchmark <name>` or `run benchmark <name1> <name2>...`


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "alamb-ghbot (via GitHub)" <gi...@apache.org>.
alamb-ghbot commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3638118348

   🤖: Benchmark completed
   
   <details><summary>Details</summary>
   <p>
   
   
   ```
   group                                          main                                   specialize
   -----                                          ----                                   ----------
   in_list/Float32/list=100/nulls=0%              1.01    306.4±3.08µs        ? ?/sec    1.00    304.6±3.45µs        ? ?/sec
   in_list/Float32/list=100/nulls=20%             1.09   394.4±15.58µs        ? ?/sec    1.00    360.4±2.39µs        ? ?/sec
   in_list/Float32/list=3/nulls=0%                1.04     14.7±0.45µs        ? ?/sec    1.00     14.2±0.07µs        ? ?/sec
   in_list/Float32/list=3/nulls=20%               1.04     19.7±0.11µs        ? ?/sec    1.00     18.9±0.44µs        ? ?/sec
   in_list/Float32/list=8/nulls=0%                1.01     29.1±0.21µs        ? ?/sec    1.00     28.7±0.37µs        ? ?/sec
   in_list/Float32/list=8/nulls=20%               1.11     39.4±0.40µs        ? ?/sec    1.00     35.4±0.36µs        ? ?/sec
   in_list/Int32/list=100/nulls=0%                1.44      6.4±0.23µs        ? ?/sec    1.00      4.4±0.08µs        ? ?/sec
   in_list/Int32/list=100/nulls=20%               1.78      8.3±0.26µs        ? ?/sec    1.00      4.7±0.03µs        ? ?/sec
   in_list/Int32/list=3/nulls=0%                  1.43      5.7±0.02µs        ? ?/sec    1.00      4.0±0.10µs        ? ?/sec
   in_list/Int32/list=3/nulls=20%                 2.13      8.8±0.28µs        ? ?/sec    1.00      4.1±0.01µs        ? ?/sec
   in_list/Int32/list=8/nulls=0%                  1.40      6.0±0.03µs        ? ?/sec    1.00      4.3±0.02µs        ? ?/sec
   in_list/Int32/list=8/nulls=20%                 2.00      8.5±0.05µs        ? ?/sec    1.00      4.3±0.11µs        ? ?/sec
   in_list/Utf8/list=100/nulls=0%/str=100         1.00    645.6±5.47µs        ? ?/sec    1.00    647.2±8.49µs        ? ?/sec
   in_list/Utf8/list=100/nulls=0%/str=12          1.01   677.4±14.75µs        ? ?/sec    1.00    669.4±5.91µs        ? ?/sec
   in_list/Utf8/list=100/nulls=0%/str=3           1.00    668.6±8.67µs        ? ?/sec    1.00   669.2±21.35µs        ? ?/sec
   in_list/Utf8/list=100/nulls=20%/str=100        1.00   600.9±16.92µs        ? ?/sec    1.00    600.2±7.27µs        ? ?/sec
   in_list/Utf8/list=100/nulls=20%/str=12         1.00    611.1±3.57µs        ? ?/sec    1.01    616.2±8.35µs        ? ?/sec
   in_list/Utf8/list=100/nulls=20%/str=3          1.00    620.0±7.35µs        ? ?/sec    1.04   642.8±37.21µs        ? ?/sec
   in_list/Utf8/list=3/nulls=0%/str=100           1.00     26.3±0.36µs        ? ?/sec    1.01     26.5±0.78µs        ? ?/sec
   in_list/Utf8/list=3/nulls=0%/str=12            1.00     26.9±1.07µs        ? ?/sec    1.00     27.0±3.55µs        ? ?/sec
   in_list/Utf8/list=3/nulls=0%/str=3             1.01     27.3±0.24µs        ? ?/sec    1.00     26.9±0.17µs        ? ?/sec
   in_list/Utf8/list=3/nulls=20%/str=100          1.00     25.7±0.34µs        ? ?/sec    1.02     26.1±0.77µs        ? ?/sec
   in_list/Utf8/list=3/nulls=20%/str=12           1.00     27.2±0.27µs        ? ?/sec    1.01     27.6±0.83µs        ? ?/sec
   in_list/Utf8/list=3/nulls=20%/str=3            1.00     26.2±0.09µs        ? ?/sec    1.01     26.4±0.56µs        ? ?/sec
   in_list/Utf8/list=8/nulls=0%/str=100           1.00     55.1±0.58µs        ? ?/sec    1.00     54.9±0.80µs        ? ?/sec
   in_list/Utf8/list=8/nulls=0%/str=12            1.00     55.8±1.13µs        ? ?/sec    1.00     55.6±0.58µs        ? ?/sec
   in_list/Utf8/list=8/nulls=0%/str=3             1.01     58.0±0.54µs        ? ?/sec    1.00     57.6±0.46µs        ? ?/sec
   in_list/Utf8/list=8/nulls=20%/str=100          1.00     52.7±0.98µs        ? ?/sec    1.04     55.0±2.64µs        ? ?/sec
   in_list/Utf8/list=8/nulls=20%/str=12           1.00     54.0±0.85µs        ? ?/sec    1.05     57.0±3.37µs        ? ?/sec
   in_list/Utf8/list=8/nulls=20%/str=3            1.00     53.8±0.34µs        ? ?/sec    1.05     56.7±3.30µs        ? ?/sec
   in_list/Utf8View/list=100/nulls=0%/str=100     1.00    596.6±6.55µs        ? ?/sec    1.04   622.4±16.62µs        ? ?/sec
   in_list/Utf8View/list=100/nulls=0%/str=12      1.00    579.8±6.15µs        ? ?/sec    1.00    578.2±8.18µs        ? ?/sec
   in_list/Utf8View/list=100/nulls=0%/str=3       1.00   578.8±11.43µs        ? ?/sec    1.00    578.1±4.43µs        ? ?/sec
   in_list/Utf8View/list=100/nulls=20%/str=100    1.00   506.4±11.79µs        ? ?/sec    1.04    528.3±7.37µs        ? ?/sec
   in_list/Utf8View/list=100/nulls=20%/str=12     1.01    513.9±5.64µs        ? ?/sec    1.00    509.8±1.93µs        ? ?/sec
   in_list/Utf8View/list=100/nulls=20%/str=3      1.00   519.3±10.43µs        ? ?/sec    1.00   517.7±11.90µs        ? ?/sec
   in_list/Utf8View/list=3/nulls=0%/str=100       1.04     22.2±0.20µs        ? ?/sec    1.00     21.3±0.80µs        ? ?/sec
   in_list/Utf8View/list=3/nulls=0%/str=12        1.04     23.2±0.20µs        ? ?/sec    1.00     22.3±0.30µs        ? ?/sec
   in_list/Utf8View/list=3/nulls=0%/str=3         1.04     23.2±0.18µs        ? ?/sec    1.00     22.3±0.36µs        ? ?/sec
   in_list/Utf8View/list=3/nulls=20%/str=100      1.01     23.1±1.01µs        ? ?/sec    1.00     22.8±0.96µs        ? ?/sec
   in_list/Utf8View/list=3/nulls=20%/str=12       1.02     23.8±0.35µs        ? ?/sec    1.00     23.2±0.21µs        ? ?/sec
   in_list/Utf8View/list=3/nulls=20%/str=3        1.02     23.6±0.73µs        ? ?/sec    1.00     23.1±0.66µs        ? ?/sec
   in_list/Utf8View/list=8/nulls=0%/str=100       1.00     49.1±1.10µs        ? ?/sec    1.01     49.4±0.51µs        ? ?/sec
   in_list/Utf8View/list=8/nulls=0%/str=12        1.02     50.7±0.45µs        ? ?/sec    1.00     49.8±0.86µs        ? ?/sec
   in_list/Utf8View/list=8/nulls=0%/str=3         1.02     50.9±1.27µs        ? ?/sec    1.00     49.7±1.10µs        ? ?/sec
   in_list/Utf8View/list=8/nulls=20%/str=100      1.00     45.1±1.33µs        ? ?/sec    1.02     45.9±1.69µs        ? ?/sec
   in_list/Utf8View/list=8/nulls=20%/str=12       1.02     46.6±0.66µs        ? ?/sec    1.00     45.9±0.56µs        ? ?/sec
   in_list/Utf8View/list=8/nulls=20%/str=3        1.02     48.6±1.04µs        ? ?/sec    1.00     47.5±0.11µs        ? ?/sec
   ```
   
   
   </p>
   </details>
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#discussion_r2603365909


##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,65 +248,414 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
-    null_count: usize,
-    values: HashSet<i32>,
+/// Threshold for switching from sorted Vec (binary search) to HashSet
+/// For small lists, binary search has better cache locality and lower overhead
+/// Maximum list size for using sorted lookup (binary search).
+/// Lists with more elements use hash lookup instead.
+const SORTED_LOOKUP_MAX_LEN: usize = 8;
+
+/// Helper to build a BooleanArray result for IN list operations.
+/// Handles SQL three-valued logic for NULL values.
+///
+/// # Arguments
+/// * `len` - Number of elements in the needle array
+/// * `needle_nulls` - Optional validity buffer from the needle array
+/// * `haystack_has_nulls` - Whether the IN list contains NULL values
+/// * `negated` - Whether this is a NOT IN operation
+/// * `contains` - Closure that returns whether needle[i] is found in the haystack
+#[inline]
+fn build_in_list_result<C>(
+    len: usize,
+    needle_nulls: Option<&NullBuffer>,
+    haystack_has_nulls: bool,
+    negated: bool,
+    contains: C,
+) -> BooleanArray
+where
+    C: Fn(usize) -> bool,
+{
+    // Use collect_bool for all paths - it's vectorized and faster than element-by-element append.
+    // Match on (needle_has_nulls, haystack_has_nulls, negated) to specialize each case.
+    match (needle_nulls, haystack_has_nulls, negated) {
+        // Haystack has nulls: result is NULL when not found (might match the NULL)
+        // values_buf == nulls_buf, so compute once and clone
+        (Some(validity), true, false) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let buf = validity.inner() & &contains_buf;
+            BooleanArray::new(buf.clone(), Some(NullBuffer::new(buf)))
+        }
+        (None, true, false) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            BooleanArray::new(buf.clone(), Some(NullBuffer::new(buf)))
+        }
+        (Some(validity), true, true) => {
+            // Compute nulls_buf via SIMD AND, then derive values_buf via XOR.
+            // Uses identity: A & !B = A ^ (A & B) to get values from nulls.
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let nulls_buf = validity.inner() & &contains_buf;
+            let values_buf = validity.inner() ^ &nulls_buf; // valid & !contains
+            BooleanArray::new(values_buf, Some(NullBuffer::new(nulls_buf)))
+        }
+        (None, true, true) => {
+            // No needle nulls, but haystack has nulls
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = !&contains_buf;
+            BooleanArray::new(values_buf, Some(NullBuffer::new(contains_buf)))
+        }
+        // Only needle has nulls: nulls_buf is just validity (reuse it directly!)
+        (Some(validity), false, false) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = validity.inner() & &contains_buf;
+            BooleanArray::new(values_buf, Some(validity.clone()))
+        }
+        (Some(validity), false, true) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = validity.inner() & &(!&contains_buf);
+            BooleanArray::new(values_buf, Some(validity.clone()))
+        }
+        // No nulls anywhere: no validity buffer needed
+        (None, false, false) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            BooleanArray::new(buf, None)
+        }
+        (None, false, true) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| !contains(i));
+            BooleanArray::new(buf, None)
+        }
+    }
 }
 
-impl Int32StaticFilter {
-    fn try_new(in_array: &ArrayRef) -> Result<Self> {
-        let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+/// Sorted lookup using binary search. Best for small lists (< 8 elements).
+struct SortedLookup<T>(Vec<T>);
 
-        let mut values = HashSet::with_capacity(in_array.len());
-        let null_count = in_array.null_count();
+impl<T: Ord> SortedLookup<T> {
+    fn new(mut values: Vec<T>) -> Self {
+        values.sort_unstable();
+        values.dedup();
+        Self(values)
+    }
 
-        for v in in_array.iter().flatten() {
-            values.insert(v);
-        }
+    #[inline]
+    fn contains(&self, value: &T) -> bool {
+        self.0.binary_search(value).is_ok()

Review Comment:
   @Dandandan and @adriangb: I opened a PR to `pydantic` at https://github.com/pydantic/datafusion/pull/48 as a POC with the bench numbers on my mac.
   
   It shows another ~70% improvement on short in-lists of primitive types, and ~40% on short utf8view in-lists as well.
   
   This is getting to be a pretty major refactor, so I'm very much in favor of "freezing" the features of this PR and leaving my further improvement to later!



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3634463950

   hey real @alamb could you whitelist `in_list` for me (might as well do Daniel and Geoffrey at the same time)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3634529621

   > ~ hey real @alamb could you whitelist `in_list` for me (might as well do Daniel and Geoffrey at the same time) ~ nvm user error
   
   @Dandandan  is already on the list
   https://github.com/alamb/datafusion-benchmarking/blob/4fb120785fa66ecbf40a45d8a5d0d5f4be17266a/scripts/scrape_comments.py#L41
   
   I can add @geoffreyclaude if he would like


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3634537320

   run benchmarks in_list
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "alamb-ghbot (via GitHub)" <gi...@apache.org>.
alamb-ghbot commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3643486839

   🤖: Benchmark completed
   
   <details><summary>Details</summary>
   <p>
   
   
   ```
   group                                          main                                   specialize
   -----                                          ----                                   ----------
   in_list/Float32/list=100/nulls=0%              49.40   304.7±1.58µs        ? ?/sec    1.00      6.2±0.12µs        ? ?/sec
   in_list/Float32/list=100/nulls=20%             66.79   390.9±6.08µs        ? ?/sec    1.00      5.9±0.02µs        ? ?/sec
   in_list/Float32/list=3/nulls=0%                2.67     14.6±0.14µs        ? ?/sec    1.00      5.5±0.06µs        ? ?/sec
   in_list/Float32/list=3/nulls=20%               3.52     20.0±1.00µs        ? ?/sec    1.00      5.7±0.02µs        ? ?/sec
   in_list/Float32/list=8/nulls=0%                5.08     29.0±0.16µs        ? ?/sec    1.00      5.7±0.03µs        ? ?/sec
   in_list/Float32/list=8/nulls=20%               6.45     39.3±0.85µs        ? ?/sec    1.00      6.1±0.37µs        ? ?/sec
   in_list/Int32/list=100/nulls=0%                1.37      5.8±0.03µs        ? ?/sec    1.00      4.3±0.06µs        ? ?/sec
   in_list/Int32/list=100/nulls=20%               1.74      8.5±0.11µs        ? ?/sec    1.00      4.9±0.07µs        ? ?/sec
   in_list/Int32/list=3/nulls=0%                  1.40      5.6±0.04µs        ? ?/sec    1.00      4.0±0.07µs        ? ?/sec
   in_list/Int32/list=3/nulls=20%                 2.22      8.7±0.05µs        ? ?/sec    1.00      3.9±0.02µs        ? ?/sec
   in_list/Int32/list=8/nulls=0%                  1.47      6.2±0.10µs        ? ?/sec    1.00      4.2±0.03µs        ? ?/sec
   in_list/Int32/list=8/nulls=20%                 1.77      8.4±0.07µs        ? ?/sec    1.00      4.7±0.03µs        ? ?/sec
   in_list/Utf8/list=100/nulls=0%/str=100         1.00    641.8±5.57µs        ? ?/sec    1.01   645.3±11.16µs        ? ?/sec
   in_list/Utf8/list=100/nulls=0%/str=12          1.00    667.3±3.33µs        ? ?/sec    1.01    673.3±3.46µs        ? ?/sec
   in_list/Utf8/list=100/nulls=0%/str=3           1.00   674.1±30.62µs        ? ?/sec    1.01    678.1±6.01µs        ? ?/sec
   in_list/Utf8/list=100/nulls=20%/str=100        1.00   596.6±21.34µs        ? ?/sec    1.00    598.5±5.10µs        ? ?/sec
   in_list/Utf8/list=100/nulls=20%/str=12         1.00    614.4±6.19µs        ? ?/sec    1.01   622.6±27.76µs        ? ?/sec
   in_list/Utf8/list=100/nulls=20%/str=3          1.00    621.9±6.25µs        ? ?/sec    1.00    623.4±3.35µs        ? ?/sec
   in_list/Utf8/list=3/nulls=0%/str=100           1.07     28.5±2.11µs        ? ?/sec    1.00     26.7±1.32µs        ? ?/sec
   in_list/Utf8/list=3/nulls=0%/str=12            1.00     26.6±0.61µs        ? ?/sec    1.05     27.8±1.36µs        ? ?/sec
   in_list/Utf8/list=3/nulls=0%/str=3             1.01     27.3±0.23µs        ? ?/sec    1.00     27.0±0.48µs        ? ?/sec
   in_list/Utf8/list=3/nulls=20%/str=100          1.00     25.9±0.40µs        ? ?/sec    1.01     26.2±0.45µs        ? ?/sec
   in_list/Utf8/list=3/nulls=20%/str=12           1.00     26.6±0.15µs        ? ?/sec    1.02     27.1±0.35µs        ? ?/sec
   in_list/Utf8/list=3/nulls=20%/str=3            1.00     26.7±0.23µs        ? ?/sec    1.01     27.0±0.31µs        ? ?/sec
   in_list/Utf8/list=8/nulls=0%/str=100           1.01     55.2±1.71µs        ? ?/sec    1.00     54.5±0.70µs        ? ?/sec
   in_list/Utf8/list=8/nulls=0%/str=12            1.00     55.9±0.49µs        ? ?/sec    1.02     57.3±1.16µs        ? ?/sec
   in_list/Utf8/list=8/nulls=0%/str=3             1.00     56.4±1.03µs        ? ?/sec    1.03     58.3±1.18µs        ? ?/sec
   in_list/Utf8/list=8/nulls=20%/str=100          1.00     52.3±0.42µs        ? ?/sec    1.03     53.9±1.92µs        ? ?/sec
   in_list/Utf8/list=8/nulls=20%/str=12           1.00     53.7±0.33µs        ? ?/sec    1.01     54.2±1.13µs        ? ?/sec
   in_list/Utf8/list=8/nulls=20%/str=3            1.00     54.3±0.56µs        ? ?/sec    1.01     54.6±0.86µs        ? ?/sec
   in_list/Utf8View/list=100/nulls=0%/str=100     1.01   597.2±11.74µs        ? ?/sec    1.00    592.2±2.03µs        ? ?/sec
   in_list/Utf8View/list=100/nulls=0%/str=12      1.00    576.3±6.37µs        ? ?/sec    1.00    576.5±2.52µs        ? ?/sec
   in_list/Utf8View/list=100/nulls=0%/str=3       1.00   578.2±13.93µs        ? ?/sec    1.00    576.3±6.54µs        ? ?/sec
   in_list/Utf8View/list=100/nulls=20%/str=100    1.00    502.6±3.13µs        ? ?/sec    1.01    505.2±4.79µs        ? ?/sec
   in_list/Utf8View/list=100/nulls=20%/str=12     1.00    508.8±2.49µs        ? ?/sec    1.00    508.8±1.82µs        ? ?/sec
   in_list/Utf8View/list=100/nulls=20%/str=3      1.00    517.0±8.52µs        ? ?/sec    1.00    515.8±6.32µs        ? ?/sec
   in_list/Utf8View/list=3/nulls=0%/str=100       1.10     22.3±0.48µs        ? ?/sec    1.00     20.2±0.07µs        ? ?/sec
   in_list/Utf8View/list=3/nulls=0%/str=12        1.05     23.2±0.34µs        ? ?/sec    1.00     22.2±0.41µs        ? ?/sec
   in_list/Utf8View/list=3/nulls=0%/str=3         1.04     23.2±0.13µs        ? ?/sec    1.00     22.4±0.43µs        ? ?/sec
   in_list/Utf8View/list=3/nulls=20%/str=100      1.02     22.7±0.12µs        ? ?/sec    1.00     22.3±0.15µs        ? ?/sec
   in_list/Utf8View/list=3/nulls=20%/str=12       1.01     23.3±0.70µs        ? ?/sec    1.00     23.2±0.25µs        ? ?/sec
   in_list/Utf8View/list=3/nulls=20%/str=3        1.00     23.5±0.33µs        ? ?/sec    1.00     23.6±0.53µs        ? ?/sec
   in_list/Utf8View/list=8/nulls=0%/str=100       1.05     48.9±1.88µs        ? ?/sec    1.00     46.8±1.57µs        ? ?/sec
   in_list/Utf8View/list=8/nulls=0%/str=12        1.03     61.1±0.24µs        ? ?/sec    1.00     59.2±1.56µs        ? ?/sec
   in_list/Utf8View/list=8/nulls=0%/str=3         1.04     61.2±0.30µs        ? ?/sec    1.00     58.8±0.34µs        ? ?/sec
   in_list/Utf8View/list=8/nulls=20%/str=100      1.02     45.1±2.00µs        ? ?/sec    1.00     44.2±0.53µs        ? ?/sec
   in_list/Utf8View/list=8/nulls=20%/str=12       1.00     46.2±1.33µs        ? ?/sec    1.03     47.5±1.98µs        ? ?/sec
   in_list/Utf8View/list=8/nulls=20%/str=3        1.00     47.8±0.74µs        ? ?/sec    1.04     49.6±1.20µs        ? ?/sec
   ```
   
   
   </p>
   </details>
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3643956111

   <img width="1019" height="413" alt="Screenshot 2025-12-11 at 4 59 23 PM" src="https://github.com/user-attachments/assets/4c9b4249-4fd5-4a47-87d9-b99894a92e1d" />
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#discussion_r2611882807


##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,99 +213,302 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
-    null_count: usize,
-    values: HashSet<i32>,
+/// Wrapper for f32 that implements Hash and Eq using IEEE 754 total ordering.
+/// This treats NaN values as equal to each other (using total_cmp).
+#[derive(Clone, Copy)]
+struct OrderedFloat32(f32);
+
+impl Hash for OrderedFloat32 {
+    fn hash<H: Hasher>(&self, state: &mut H) {
+        self.0.to_ne_bytes().hash(state);
+    }
 }
 
-impl Int32StaticFilter {
-    fn try_new(in_array: &ArrayRef) -> Result<Self> {
-        let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+impl PartialEq for OrderedFloat32 {
+    fn eq(&self, other: &Self) -> bool {
+        self.0.total_cmp(&other.0).is_eq()
+    }
+}
 
-        let mut values = HashSet::with_capacity(in_array.len());
-        let null_count = in_array.null_count();
+impl Eq for OrderedFloat32 {}
 
-        for v in in_array.iter().flatten() {
-            values.insert(v);
-        }
+impl From<f32> for OrderedFloat32 {
+    fn from(v: f32) -> Self {
+        Self(v)
+    }
+}
 
-        Ok(Self { null_count, values })
+/// Wrapper for f64 that implements Hash and Eq using IEEE 754 total ordering.
+/// This treats NaN values as equal to each other (using total_cmp).
+#[derive(Clone, Copy)]
+struct OrderedFloat64(f64);
+
+impl Hash for OrderedFloat64 {
+    fn hash<H: Hasher>(&self, state: &mut H) {
+        self.0.to_ne_bytes().hash(state);
     }
 }
 
-impl StaticFilter for Int32StaticFilter {
-    fn null_count(&self) -> usize {
-        self.null_count
+impl PartialEq for OrderedFloat64 {
+    fn eq(&self, other: &Self) -> bool {
+        self.0.total_cmp(&other.0).is_eq()
     }
+}
 
-    fn contains(&self, v: &dyn Array, negated: bool) -> Result<BooleanArray> {
-        // Handle dictionary arrays by recursing on the values
-        downcast_dictionary_array! {
-            v => {
-                let values_contains = self.contains(v.values().as_ref(), negated)?;
-                let result = take(&values_contains, v.keys(), None)?;
-                return Ok(downcast_array(result.as_ref()))
+impl Eq for OrderedFloat64 {}
+
+impl From<f64> for OrderedFloat64 {
+    fn from(v: f64) -> Self {
+        Self(v)
+    }
+}
+
+// Macro to generate specialized StaticFilter implementations for primitive types
+macro_rules! primitive_static_filter {
+    ($Name:ident, $ArrowType:ty) => {
+        struct $Name {
+            null_count: usize,
+            values: HashSet<<$ArrowType as ArrowPrimitiveType>::Native>,
+        }
+
+        impl $Name {
+            fn try_new(in_array: &ArrayRef) -> Result<Self> {
+                let in_array = in_array
+                    .as_primitive_opt::<$ArrowType>()
+                    .ok_or_else(|| exec_datafusion_err!("Failed to downcast an array to a '{}' array", stringify!($ArrowType)))?;
+
+                let mut values = HashSet::with_capacity(in_array.len());
+                let null_count = in_array.null_count();
+
+                for v in in_array.iter().flatten() {
+                    values.insert(v);
+                }
+
+                Ok(Self { null_count, values })
             }
-            _ => {}
         }
 
-        let v = v
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
-
-        let haystack_has_nulls = self.null_count > 0;
-        let has_nulls = v.null_count() > 0 || haystack_has_nulls;
-
-        let result = match (has_nulls, negated) {
-            (true, false) => {
-                // needle has nulls, not negated
-                BooleanArray::from_iter(v.iter().map(|value| match value {
-                    None => None,
-                    Some(v) => {
-                        if self.values.contains(&v) {
-                            Some(true)
-                        } else if haystack_has_nulls {
-                            None
+        impl StaticFilter for $Name {
+            fn null_count(&self) -> usize {
+                self.null_count
+            }
+
+            fn contains(&self, v: &dyn Array, negated: bool) -> Result<BooleanArray> {
+                // Handle dictionary arrays by recursing on the values
+                downcast_dictionary_array! {
+                    v => {
+                        let values_contains = self.contains(v.values().as_ref(), negated)?;
+                        let result = take(&values_contains, v.keys(), None)?;
+                        return Ok(downcast_array(result.as_ref()))
+                    }
+                    _ => {}
+                }
+
+                let v = v
+                    .as_primitive_opt::<$ArrowType>()
+                    .ok_or_else(|| exec_datafusion_err!("Failed to downcast an array to a '{}' array", stringify!($ArrowType)))?;
+
+                let haystack_has_nulls = self.null_count > 0;
+
+                let needle_values = v.values();
+                let needle_nulls = v.nulls();
+                let needle_has_nulls = v.null_count() > 0;
+
+                // Compute the "contains" result using collect_bool (fast batched approach)
+                // This ignores nulls - we handle them separately
+                let contains_buffer = if negated {
+                    BooleanBuffer::collect_bool(needle_values.len(), |i| {
+                        !self.values.contains(&needle_values[i])
+                    })
+                } else {
+                    BooleanBuffer::collect_bool(needle_values.len(), |i| {
+                        self.values.contains(&needle_values[i])
+                    })
+                };
+
+                // Compute the null mask
+                // Output is null when:
+                // 1. needle value is null, OR
+                // 2. needle value is not in set AND haystack has nulls
+                let result_nulls = match (needle_has_nulls, haystack_has_nulls) {
+                    (false, false) => {
+                        // No nulls anywhere
+                        None
+                    }
+                    (true, false) => {
+                        // Only needle has nulls - just use needle's null mask
+                        needle_nulls.cloned()
+                    }
+                    (false, true) => {
+                        // Only haystack has nulls - null where not-in-set

Review Comment:
   Thanks, this is way more readable!



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "Dandandan (via GitHub)" <gi...@apache.org>.
Dandandan commented on code in PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#discussion_r2549507569


##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,68 +206,122 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
-    null_count: usize,
-    values: HashSet<i32>,
-}
+// Macro to generate specialized StaticFilter implementations for primitive types
+macro_rules! primitive_static_filter {
+    ($Name:ident, $ArrowType:ty) => {
+        struct $Name {
+            null_count: usize,
+            values: HashSet<<$ArrowType as ArrowPrimitiveType>::Native>,
+        }
 
-impl Int32StaticFilter {
-    fn try_new(in_array: &ArrayRef) -> Result<Self> {
-        let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+        impl $Name {
+            fn try_new(in_array: &ArrayRef) -> Result<Self> {
+                let in_array = in_array
+                    .as_primitive_opt::<$ArrowType>()
+                    .ok_or_else(|| exec_datafusion_err!(format!("Failed to downcast an array to a '{}' array", stringify!($ArrowType))))?;
 
-        let mut values = HashSet::with_capacity(in_array.len());
-        let null_count = in_array.null_count();
+                let mut values = HashSet::with_capacity(in_array.len());
+                let null_count = in_array.null_count();
+
+                for v in in_array.iter().flatten() {
+                    values.insert(v);
+                }
 
-        for v in in_array.iter().flatten() {
-            values.insert(v);
+                Ok(Self { null_count, values })
+            }
         }
 
-        Ok(Self { null_count, values })
-    }
-}
+        impl StaticFilter for $Name {
+            fn null_count(&self) -> usize {
+                self.null_count
+            }
 
-impl StaticFilter for Int32StaticFilter {
-    fn null_count(&self) -> usize {
-        self.null_count
-    }
+            fn contains(&self, v: &dyn Array, negated: bool) -> Result<BooleanArray> {
+                // Handle dictionary arrays by recursing on the values
+                downcast_dictionary_array! {
+                    v => {
+                        let values_contains = self.contains(v.values().as_ref(), negated)?;
+                        let result = take(&values_contains, v.keys(), None)?;
+                        return Ok(downcast_array(result.as_ref()))
+                    }
+                    _ => {}
+                }
 
-    fn contains(&self, v: &dyn Array, negated: bool) -> Result<BooleanArray> {
-        let v = v
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
-
-        let result = match (v.null_count() > 0, negated) {
-            (true, false) => {
-                // has nulls, not negated"
-                BooleanArray::from_iter(
-                    v.iter().map(|value| Some(self.values.contains(&value?))),
-                )
-            }
-            (true, true) => {
-                // has nulls, negated
-                BooleanArray::from_iter(
-                    v.iter().map(|value| Some(!self.values.contains(&value?))),
-                )
-            }
-            (false, false) => {
-                //no null, not negated
-                BooleanArray::from_iter(
-                    v.values().iter().map(|value| self.values.contains(value)),
-                )
-            }
-            (false, true) => {
-                // no null, negated
-                BooleanArray::from_iter(
-                    v.values().iter().map(|value| !self.values.contains(value)),
-                )
+                let v = v
+                    .as_primitive_opt::<$ArrowType>()
+                    .ok_or_else(|| exec_datafusion_err!(format!("Failed to downcast an array to a '{}' array", stringify!($ArrowType))))?;
+
+                let haystack_has_nulls = self.null_count > 0;
+
+                let result = match (v.null_count() > 0, haystack_has_nulls, negated) {
+                    (true, _, false) | (false, true, false) => {
+                        // Either needle or haystack has nulls, not negated
+                        BooleanArray::from_iter(v.iter().map(|value| {
+                            match value {
+                                // SQL three-valued logic: null IN (...) is always null
+                                None => None,
+                                Some(v) => {
+                                    if self.values.contains(&v) {
+                                        Some(true)
+                                    } else if haystack_has_nulls {
+                                        // value not in set, but set has nulls -> null
+                                        None
+                                    } else {
+                                        Some(false)
+                                    }
+                                }
+                            }
+                        }))
+                    }
+                    (true, _, true) | (false, true, true) => {
+                        // Either needle or haystack has nulls, negated
+                        BooleanArray::from_iter(v.iter().map(|value| {
+                            match value {
+                                // SQL three-valued logic: null NOT IN (...) is always null
+                                None => None,
+                                Some(v) => {
+                                    if self.values.contains(&v) {
+                                        Some(false)
+                                    } else if haystack_has_nulls {
+                                        // value not in set, but set has nulls -> null
+                                        None
+                                    } else {
+                                        Some(true)
+                                    }
+                                }
+                            }
+                        }))
+                    }
+                    (false, false, false) => {
+                        // no nulls anywhere, not negated
+                        BooleanArray::from_iter(

Review Comment:
   `BooleanBuffer::collect_bool is faster`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3643589105

   I'll kick off some general benchmarks and if those look good and there's no more feedback I'll merge later today or tomorrow morning.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on code in PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#discussion_r2611759971


##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,99 +213,302 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
-    null_count: usize,
-    values: HashSet<i32>,
+/// Wrapper for f32 that implements Hash and Eq using IEEE 754 total ordering.
+/// This treats NaN values as equal to each other (using total_cmp).
+#[derive(Clone, Copy)]
+struct OrderedFloat32(f32);
+
+impl Hash for OrderedFloat32 {
+    fn hash<H: Hasher>(&self, state: &mut H) {
+        self.0.to_ne_bytes().hash(state);
+    }
 }
 
-impl Int32StaticFilter {
-    fn try_new(in_array: &ArrayRef) -> Result<Self> {
-        let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+impl PartialEq for OrderedFloat32 {
+    fn eq(&self, other: &Self) -> bool {
+        self.0.total_cmp(&other.0).is_eq()
+    }
+}
 
-        let mut values = HashSet::with_capacity(in_array.len());
-        let null_count = in_array.null_count();
+impl Eq for OrderedFloat32 {}
 
-        for v in in_array.iter().flatten() {
-            values.insert(v);
-        }
+impl From<f32> for OrderedFloat32 {
+    fn from(v: f32) -> Self {
+        Self(v)
+    }
+}
 
-        Ok(Self { null_count, values })
+/// Wrapper for f64 that implements Hash and Eq using IEEE 754 total ordering.
+/// This treats NaN values as equal to each other (using total_cmp).
+#[derive(Clone, Copy)]
+struct OrderedFloat64(f64);
+
+impl Hash for OrderedFloat64 {
+    fn hash<H: Hasher>(&self, state: &mut H) {
+        self.0.to_ne_bytes().hash(state);
     }
 }
 
-impl StaticFilter for Int32StaticFilter {
-    fn null_count(&self) -> usize {
-        self.null_count
+impl PartialEq for OrderedFloat64 {
+    fn eq(&self, other: &Self) -> bool {
+        self.0.total_cmp(&other.0).is_eq()
     }
+}
 
-    fn contains(&self, v: &dyn Array, negated: bool) -> Result<BooleanArray> {
-        // Handle dictionary arrays by recursing on the values
-        downcast_dictionary_array! {
-            v => {
-                let values_contains = self.contains(v.values().as_ref(), negated)?;
-                let result = take(&values_contains, v.keys(), None)?;
-                return Ok(downcast_array(result.as_ref()))
+impl Eq for OrderedFloat64 {}
+
+impl From<f64> for OrderedFloat64 {
+    fn from(v: f64) -> Self {
+        Self(v)
+    }
+}
+
+// Macro to generate specialized StaticFilter implementations for primitive types
+macro_rules! primitive_static_filter {
+    ($Name:ident, $ArrowType:ty) => {
+        struct $Name {
+            null_count: usize,
+            values: HashSet<<$ArrowType as ArrowPrimitiveType>::Native>,
+        }
+
+        impl $Name {
+            fn try_new(in_array: &ArrayRef) -> Result<Self> {
+                let in_array = in_array
+                    .as_primitive_opt::<$ArrowType>()
+                    .ok_or_else(|| exec_datafusion_err!("Failed to downcast an array to a '{}' array", stringify!($ArrowType)))?;
+
+                let mut values = HashSet::with_capacity(in_array.len());
+                let null_count = in_array.null_count();
+
+                for v in in_array.iter().flatten() {
+                    values.insert(v);
+                }
+
+                Ok(Self { null_count, values })
             }
-            _ => {}
         }
 
-        let v = v
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
-
-        let haystack_has_nulls = self.null_count > 0;
-        let has_nulls = v.null_count() > 0 || haystack_has_nulls;
-
-        let result = match (has_nulls, negated) {
-            (true, false) => {
-                // needle has nulls, not negated
-                BooleanArray::from_iter(v.iter().map(|value| match value {
-                    None => None,
-                    Some(v) => {
-                        if self.values.contains(&v) {
-                            Some(true)
-                        } else if haystack_has_nulls {
-                            None
+        impl StaticFilter for $Name {
+            fn null_count(&self) -> usize {
+                self.null_count
+            }
+
+            fn contains(&self, v: &dyn Array, negated: bool) -> Result<BooleanArray> {
+                // Handle dictionary arrays by recursing on the values
+                downcast_dictionary_array! {
+                    v => {
+                        let values_contains = self.contains(v.values().as_ref(), negated)?;
+                        let result = take(&values_contains, v.keys(), None)?;
+                        return Ok(downcast_array(result.as_ref()))
+                    }
+                    _ => {}
+                }
+
+                let v = v
+                    .as_primitive_opt::<$ArrowType>()
+                    .ok_or_else(|| exec_datafusion_err!("Failed to downcast an array to a '{}' array", stringify!($ArrowType)))?;
+
+                let haystack_has_nulls = self.null_count > 0;
+
+                let needle_values = v.values();
+                let needle_nulls = v.nulls();
+                let needle_has_nulls = v.null_count() > 0;
+
+                // Compute the "contains" result using collect_bool (fast batched approach)
+                // This ignores nulls - we handle them separately
+                let contains_buffer = if negated {
+                    BooleanBuffer::collect_bool(needle_values.len(), |i| {
+                        !self.values.contains(&needle_values[i])
+                    })
+                } else {
+                    BooleanBuffer::collect_bool(needle_values.len(), |i| {
+                        self.values.contains(&needle_values[i])
+                    })
+                };
+
+                // Compute the null mask
+                // Output is null when:
+                // 1. needle value is null, OR
+                // 2. needle value is not in set AND haystack has nulls
+                let result_nulls = match (needle_has_nulls, haystack_has_nulls) {
+                    (false, false) => {
+                        // No nulls anywhere
+                        None
+                    }
+                    (true, false) => {
+                        // Only needle has nulls - just use needle's null mask
+                        needle_nulls.cloned()
+                    }
+                    (false, true) => {
+                        // Only haystack has nulls - null where not-in-set

Review Comment:
   0b5a9c9



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on code in PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#discussion_r2611760948


##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,99 +213,302 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
-    null_count: usize,
-    values: HashSet<i32>,
+/// Wrapper for f32 that implements Hash and Eq using IEEE 754 total ordering.
+/// This treats NaN values as equal to each other (using total_cmp).
+#[derive(Clone, Copy)]
+struct OrderedFloat32(f32);
+
+impl Hash for OrderedFloat32 {
+    fn hash<H: Hasher>(&self, state: &mut H) {
+        self.0.to_ne_bytes().hash(state);
+    }
 }
 
-impl Int32StaticFilter {
-    fn try_new(in_array: &ArrayRef) -> Result<Self> {
-        let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+impl PartialEq for OrderedFloat32 {
+    fn eq(&self, other: &Self) -> bool {
+        self.0.total_cmp(&other.0).is_eq()

Review Comment:
   b6404e5bc



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3566518295

   🤖 `./gh_compare_branch.sh` [Benchmark Script](https://github.com/alamb/datafusion-benchmarking/blob/main/gh_compare_branch.sh) Running
   Linux aal-dev 6.14.0-1018-gcp #19~24.04.1-Ubuntu SMP Wed Sep 24 23:23:09 UTC 2025 x86_64 x86_64 x86_64 GNU/Linux
   Comparing specialize (1e4782f1cde36a83398002a4730ff96123b547a3) to 7d8b8602ad1be2f61f6a8ebb253ace9d85304ea7 [diff](https://github.com/apache/datafusion/compare/7d8b8602ad1be2f61f6a8ebb253ace9d85304ea7..1e4782f1cde36a83398002a4730ff96123b547a3) using:  tpch_mem clickbench_partitioned clickbench_extended
   Results will be posted here when complete
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3566687657

   🤖: Benchmark completed
   
   <details><summary>Details</summary>
   <p>
   
   
   ```
   group                                       main                                   specialize
   -----                                       ----                                   ----------
   in_list_f32 (1024, 0) IN (1, 0)             1.16      4.2±0.01µs        ? ?/sec    1.00      3.6±0.02µs        ? ?/sec
   in_list_f32 (1024, 0) IN (10, 0)            1.16      4.2±0.01µs        ? ?/sec    1.00      3.6±0.02µs        ? ?/sec
   in_list_f32 (1024, 0) IN (100, 0)           1.16      4.3±0.01µs        ? ?/sec    1.00      3.7±0.01µs        ? ?/sec
   in_list_f32 (1024, 0) IN (3, 0)             1.17      4.3±0.10µs        ? ?/sec    1.00      3.6±0.01µs        ? ?/sec
   in_list_f32 (1024, 0.2) IN (1, 0)           1.00      5.1±0.02µs        ? ?/sec    1.13      5.8±0.07µs        ? ?/sec
   in_list_f32 (1024, 0.2) IN (10, 0)          1.00      5.3±0.03µs        ? ?/sec    1.09      5.7±0.02µs        ? ?/sec
   in_list_f32 (1024, 0.2) IN (100, 0)         1.00      5.3±0.04µs        ? ?/sec    1.13      5.9±0.10µs        ? ?/sec
   in_list_f32 (1024, 0.2) IN (3, 0)           1.00      5.2±0.04µs        ? ?/sec    1.12      5.8±0.05µs        ? ?/sec
   in_list_i32 (1024, 0) IN (1, 0)             1.00      4.3±0.01µs        ? ?/sec    1.11      4.7±0.02µs        ? ?/sec
   in_list_i32 (1024, 0) IN (10, 0)            1.00      4.2±0.01µs        ? ?/sec    1.11      4.7±0.04µs        ? ?/sec
   in_list_i32 (1024, 0) IN (100, 0)           1.00      4.3±0.01µs        ? ?/sec    1.11      4.7±0.01µs        ? ?/sec
   in_list_i32 (1024, 0) IN (3, 0)             1.00      4.3±0.01µs        ? ?/sec    1.11      4.7±0.07µs        ? ?/sec
   in_list_i32 (1024, 0.2) IN (1, 0)           1.00      5.2±0.02µs        ? ?/sec    1.32      6.8±0.39µs        ? ?/sec
   in_list_i32 (1024, 0.2) IN (10, 0)          1.00      5.2±0.02µs        ? ?/sec    1.25      6.5±0.03µs        ? ?/sec
   in_list_i32 (1024, 0.2) IN (100, 0)         1.00      5.2±0.03µs        ? ?/sec    1.16      6.1±0.06µs        ? ?/sec
   in_list_i32 (1024, 0.2) IN (3, 0)           1.00      5.2±0.02µs        ? ?/sec    1.30      6.8±0.03µs        ? ?/sec
   in_list_utf8(10) (1024, 0) IN (1, 0)        1.16      4.5±0.02µs        ? ?/sec    1.00      3.9±0.01µs        ? ?/sec
   in_list_utf8(10) (1024, 0) IN (10, 0)       1.16      4.5±0.01µs        ? ?/sec    1.00      3.9±0.01µs        ? ?/sec
   in_list_utf8(10) (1024, 0) IN (100, 0)      1.16      4.5±0.03µs        ? ?/sec    1.00      3.9±0.01µs        ? ?/sec
   in_list_utf8(10) (1024, 0) IN (3, 0)        1.16      4.5±0.04µs        ? ?/sec    1.00      3.9±0.01µs        ? ?/sec
   in_list_utf8(10) (1024, 0.2) IN (1, 0)      1.06      5.9±0.03µs        ? ?/sec    1.00      5.6±0.04µs        ? ?/sec
   in_list_utf8(10) (1024, 0.2) IN (10, 0)     1.09      6.0±0.06µs        ? ?/sec    1.00      5.5±0.03µs        ? ?/sec
   in_list_utf8(10) (1024, 0.2) IN (100, 0)    1.07      6.0±0.03µs        ? ?/sec    1.00      5.6±0.03µs        ? ?/sec
   in_list_utf8(10) (1024, 0.2) IN (3, 0)      1.10      6.1±0.04µs        ? ?/sec    1.00      5.6±0.03µs        ? ?/sec
   in_list_utf8(20) (1024, 0) IN (1, 0)        1.16      4.5±0.02µs        ? ?/sec    1.00      3.9±0.01µs        ? ?/sec
   in_list_utf8(20) (1024, 0) IN (10, 0)       1.16      4.5±0.01µs        ? ?/sec    1.00      3.9±0.01µs        ? ?/sec
   in_list_utf8(20) (1024, 0) IN (100, 0)      1.15      4.5±0.04µs        ? ?/sec    1.00      3.9±0.03µs        ? ?/sec
   in_list_utf8(20) (1024, 0) IN (3, 0)        1.14      4.6±0.01µs        ? ?/sec    1.00      4.0±0.03µs        ? ?/sec
   in_list_utf8(20) (1024, 0.2) IN (1, 0)      1.06      6.0±0.02µs        ? ?/sec    1.00      5.7±0.03µs        ? ?/sec
   in_list_utf8(20) (1024, 0.2) IN (10, 0)     1.07      6.0±0.03µs        ? ?/sec    1.00      5.6±0.03µs        ? ?/sec
   in_list_utf8(20) (1024, 0.2) IN (100, 0)    1.09      6.1±0.03µs        ? ?/sec    1.00      5.6±0.02µs        ? ?/sec
   in_list_utf8(20) (1024, 0.2) IN (3, 0)      1.04      6.1±0.03µs        ? ?/sec    1.00      5.8±0.05µs        ? ?/sec
   in_list_utf8(5) (1024, 0) IN (1, 0)         1.15      4.5±0.01µs        ? ?/sec    1.00      4.0±0.01µs        ? ?/sec
   in_list_utf8(5) (1024, 0) IN (10, 0)        1.16      4.5±0.03µs        ? ?/sec    1.00      3.9±0.01µs        ? ?/sec
   in_list_utf8(5) (1024, 0) IN (100, 0)       1.16      4.5±0.01µs        ? ?/sec    1.00      3.9±0.00µs        ? ?/sec
   in_list_utf8(5) (1024, 0) IN (3, 0)         1.14      4.5±0.03µs        ? ?/sec    1.00      4.0±0.02µs        ? ?/sec
   in_list_utf8(5) (1024, 0.2) IN (1, 0)       1.06      5.9±0.04µs        ? ?/sec    1.00      5.5±0.04µs        ? ?/sec
   in_list_utf8(5) (1024, 0.2) IN (10, 0)      1.10      6.1±0.04µs        ? ?/sec    1.00      5.5±0.03µs        ? ?/sec
   in_list_utf8(5) (1024, 0.2) IN (100, 0)     1.11      6.0±0.03µs        ? ?/sec    1.00      5.4±0.03µs        ? ?/sec
   in_list_utf8(5) (1024, 0.2) IN (3, 0)       1.11      6.1±0.06µs        ? ?/sec    1.00      5.5±0.04µs        ? ?/sec
   ```
   
   
   </p>
   </details>
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "Dandandan (via GitHub)" <gi...@apache.org>.
Dandandan commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3567537044

   > 🤖: Benchmark completed
   > 
   > Details
   > 
   > ```
   > group                                       main                                   specialize
   > -----                                       ----                                   ----------
   > in_list_f32 (1024, 0) IN (1, 0)             1.16      4.2±0.01µs        ? ?/sec    1.00      3.6±0.02µs        ? ?/sec
   > in_list_f32 (1024, 0) IN (10, 0)            1.16      4.2±0.01µs        ? ?/sec    1.00      3.6±0.02µs        ? ?/sec
   > in_list_f32 (1024, 0) IN (100, 0)           1.16      4.3±0.01µs        ? ?/sec    1.00      3.7±0.01µs        ? ?/sec
   > in_list_f32 (1024, 0) IN (3, 0)             1.17      4.3±0.10µs        ? ?/sec    1.00      3.6±0.01µs        ? ?/sec
   > in_list_f32 (1024, 0.2) IN (1, 0)           1.00      5.1±0.02µs        ? ?/sec    1.13      5.8±0.07µs        ? ?/sec
   > in_list_f32 (1024, 0.2) IN (10, 0)          1.00      5.3±0.03µs        ? ?/sec    1.09      5.7±0.02µs        ? ?/sec
   > in_list_f32 (1024, 0.2) IN (100, 0)         1.00      5.3±0.04µs        ? ?/sec    1.13      5.9±0.10µs        ? ?/sec
   > in_list_f32 (1024, 0.2) IN (3, 0)           1.00      5.2±0.04µs        ? ?/sec    1.12      5.8±0.05µs        ? ?/sec
   > in_list_i32 (1024, 0) IN (1, 0)             1.00      4.3±0.01µs        ? ?/sec    1.11      4.7±0.02µs        ? ?/sec
   > in_list_i32 (1024, 0) IN (10, 0)            1.00      4.2±0.01µs        ? ?/sec    1.11      4.7±0.04µs        ? ?/sec
   > in_list_i32 (1024, 0) IN (100, 0)           1.00      4.3±0.01µs        ? ?/sec    1.11      4.7±0.01µs        ? ?/sec
   > in_list_i32 (1024, 0) IN (3, 0)             1.00      4.3±0.01µs        ? ?/sec    1.11      4.7±0.07µs        ? ?/sec
   > in_list_i32 (1024, 0.2) IN (1, 0)           1.00      5.2±0.02µs        ? ?/sec    1.32      6.8±0.39µs        ? ?/sec
   > in_list_i32 (1024, 0.2) IN (10, 0)          1.00      5.2±0.02µs        ? ?/sec    1.25      6.5±0.03µs        ? ?/sec
   > in_list_i32 (1024, 0.2) IN (100, 0)         1.00      5.2±0.03µs        ? ?/sec    1.16      6.1±0.06µs        ? ?/sec
   > in_list_i32 (1024, 0.2) IN (3, 0)           1.00      5.2±0.02µs        ? ?/sec    1.30      6.8±0.03µs        ? ?/sec
   > in_list_utf8(10) (1024, 0) IN (1, 0)        1.16      4.5±0.02µs        ? ?/sec    1.00      3.9±0.01µs        ? ?/sec
   > in_list_utf8(10) (1024, 0) IN (10, 0)       1.16      4.5±0.01µs        ? ?/sec    1.00      3.9±0.01µs        ? ?/sec
   > in_list_utf8(10) (1024, 0) IN (100, 0)      1.16      4.5±0.03µs        ? ?/sec    1.00      3.9±0.01µs        ? ?/sec
   > in_list_utf8(10) (1024, 0) IN (3, 0)        1.16      4.5±0.04µs        ? ?/sec    1.00      3.9±0.01µs        ? ?/sec
   > in_list_utf8(10) (1024, 0.2) IN (1, 0)      1.06      5.9±0.03µs        ? ?/sec    1.00      5.6±0.04µs        ? ?/sec
   > in_list_utf8(10) (1024, 0.2) IN (10, 0)     1.09      6.0±0.06µs        ? ?/sec    1.00      5.5±0.03µs        ? ?/sec
   > in_list_utf8(10) (1024, 0.2) IN (100, 0)    1.07      6.0±0.03µs        ? ?/sec    1.00      5.6±0.03µs        ? ?/sec
   > in_list_utf8(10) (1024, 0.2) IN (3, 0)      1.10      6.1±0.04µs        ? ?/sec    1.00      5.6±0.03µs        ? ?/sec
   > in_list_utf8(20) (1024, 0) IN (1, 0)        1.16      4.5±0.02µs        ? ?/sec    1.00      3.9±0.01µs        ? ?/sec
   > in_list_utf8(20) (1024, 0) IN (10, 0)       1.16      4.5±0.01µs        ? ?/sec    1.00      3.9±0.01µs        ? ?/sec
   > in_list_utf8(20) (1024, 0) IN (100, 0)      1.15      4.5±0.04µs        ? ?/sec    1.00      3.9±0.03µs        ? ?/sec
   > in_list_utf8(20) (1024, 0) IN (3, 0)        1.14      4.6±0.01µs        ? ?/sec    1.00      4.0±0.03µs        ? ?/sec
   > in_list_utf8(20) (1024, 0.2) IN (1, 0)      1.06      6.0±0.02µs        ? ?/sec    1.00      5.7±0.03µs        ? ?/sec
   > in_list_utf8(20) (1024, 0.2) IN (10, 0)     1.07      6.0±0.03µs        ? ?/sec    1.00      5.6±0.03µs        ? ?/sec
   > in_list_utf8(20) (1024, 0.2) IN (100, 0)    1.09      6.1±0.03µs        ? ?/sec    1.00      5.6±0.02µs        ? ?/sec
   > in_list_utf8(20) (1024, 0.2) IN (3, 0)      1.04      6.1±0.03µs        ? ?/sec    1.00      5.8±0.05µs        ? ?/sec
   > in_list_utf8(5) (1024, 0) IN (1, 0)         1.15      4.5±0.01µs        ? ?/sec    1.00      4.0±0.01µs        ? ?/sec
   > in_list_utf8(5) (1024, 0) IN (10, 0)        1.16      4.5±0.03µs        ? ?/sec    1.00      3.9±0.01µs        ? ?/sec
   > in_list_utf8(5) (1024, 0) IN (100, 0)       1.16      4.5±0.01µs        ? ?/sec    1.00      3.9±0.00µs        ? ?/sec
   > in_list_utf8(5) (1024, 0) IN (3, 0)         1.14      4.5±0.03µs        ? ?/sec    1.00      4.0±0.02µs        ? ?/sec
   > in_list_utf8(5) (1024, 0.2) IN (1, 0)       1.06      5.9±0.04µs        ? ?/sec    1.00      5.5±0.04µs        ? ?/sec
   > in_list_utf8(5) (1024, 0.2) IN (10, 0)      1.10      6.1±0.04µs        ? ?/sec    1.00      5.5±0.03µs        ? ?/sec
   > in_list_utf8(5) (1024, 0.2) IN (100, 0)     1.11      6.0±0.03µs        ? ?/sec    1.00      5.4±0.03µs        ? ?/sec
   > in_list_utf8(5) (1024, 0.2) IN (3, 0)       1.11      6.1±0.06µs        ? ?/sec    1.00      5.5±0.04µs        ? ?/sec
   > ```
   
   Results seems a bit mixed?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#discussion_r2603433605


##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,65 +248,414 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
-    null_count: usize,
-    values: HashSet<i32>,
+/// Threshold for switching from sorted Vec (binary search) to HashSet
+/// For small lists, binary search has better cache locality and lower overhead
+/// Maximum list size for using sorted lookup (binary search).
+/// Lists with more elements use hash lookup instead.
+const SORTED_LOOKUP_MAX_LEN: usize = 8;
+
+/// Helper to build a BooleanArray result for IN list operations.
+/// Handles SQL three-valued logic for NULL values.
+///
+/// # Arguments
+/// * `len` - Number of elements in the needle array
+/// * `needle_nulls` - Optional validity buffer from the needle array
+/// * `haystack_has_nulls` - Whether the IN list contains NULL values
+/// * `negated` - Whether this is a NOT IN operation
+/// * `contains` - Closure that returns whether needle[i] is found in the haystack
+#[inline]
+fn build_in_list_result<C>(
+    len: usize,
+    needle_nulls: Option<&NullBuffer>,
+    haystack_has_nulls: bool,
+    negated: bool,
+    contains: C,
+) -> BooleanArray
+where
+    C: Fn(usize) -> bool,
+{
+    // Use collect_bool for all paths - it's vectorized and faster than element-by-element append.
+    // Match on (needle_has_nulls, haystack_has_nulls, negated) to specialize each case.
+    match (needle_nulls, haystack_has_nulls, negated) {
+        // Haystack has nulls: result is NULL when not found (might match the NULL)
+        // values_buf == nulls_buf, so compute once and clone
+        (Some(validity), true, false) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let buf = validity.inner() & &contains_buf;
+            BooleanArray::new(buf.clone(), Some(NullBuffer::new(buf)))
+        }
+        (None, true, false) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            BooleanArray::new(buf.clone(), Some(NullBuffer::new(buf)))
+        }
+        (Some(validity), true, true) => {
+            // Compute nulls_buf via SIMD AND, then derive values_buf via XOR.
+            // Uses identity: A & !B = A ^ (A & B) to get values from nulls.
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let nulls_buf = validity.inner() & &contains_buf;
+            let values_buf = validity.inner() ^ &nulls_buf; // valid & !contains
+            BooleanArray::new(values_buf, Some(NullBuffer::new(nulls_buf)))
+        }
+        (None, true, true) => {
+            // No needle nulls, but haystack has nulls
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = !&contains_buf;
+            BooleanArray::new(values_buf, Some(NullBuffer::new(contains_buf)))
+        }
+        // Only needle has nulls: nulls_buf is just validity (reuse it directly!)
+        (Some(validity), false, false) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = validity.inner() & &contains_buf;
+            BooleanArray::new(values_buf, Some(validity.clone()))
+        }
+        (Some(validity), false, true) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = validity.inner() & &(!&contains_buf);
+            BooleanArray::new(values_buf, Some(validity.clone()))
+        }
+        // No nulls anywhere: no validity buffer needed
+        (None, false, false) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            BooleanArray::new(buf, None)
+        }
+        (None, false, true) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| !contains(i));
+            BooleanArray::new(buf, None)
+        }
+    }
 }
 
-impl Int32StaticFilter {
-    fn try_new(in_array: &ArrayRef) -> Result<Self> {
-        let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+/// Sorted lookup using binary search. Best for small lists (< 8 elements).
+struct SortedLookup<T>(Vec<T>);
 
-        let mut values = HashSet::with_capacity(in_array.len());
-        let null_count = in_array.null_count();
+impl<T: Ord> SortedLookup<T> {
+    fn new(mut values: Vec<T>) -> Self {
+        values.sort_unstable();
+        values.dedup();
+        Self(values)
+    }
 
-        for v in in_array.iter().flatten() {
-            values.insert(v);
-        }
+    #[inline]
+    fn contains(&self, value: &T) -> bool {
+        self.0.binary_search(value).is_ok()

Review Comment:
   > smaller targeted PRs off of that
   That's definitely the way to go! I'll fork off an issue from https://github.com/apache/datafusion/issues/18824.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "alamb-ghbot (via GitHub)" <gi...@apache.org>.
alamb-ghbot commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3634469414

   🤖 `./gh_compare_branch_bench.sh` [compare_branch_bench.sh](https://github.com/alamb/datafusion-benchmarking/blob/main/scripts/compare_branch_bench.sh) Running
   Linux aal-dev 6.14.0-1018-gcp #19~24.04.1-Ubuntu SMP Wed Sep 24 23:23:09 UTC 2025 x86_64 x86_64 x86_64 GNU/Linux
   Comparing specialize (d11d7ae6d79acc1cc4e815fd01e37bce6afae0ad) to e8a0829b7a2044ab477784d60ed2d208b97f5042 [diff](https://github.com/apache/datafusion/compare/e8a0829b7a2044ab477784d60ed2d208b97f5042..d11d7ae6d79acc1cc4e815fd01e37bce6afae0ad)
   BENCH_NAME=in_list
   BENCH_COMMAND=cargo bench --all-features --bench in_list
   BENCH_FILTER=
   BENCH_BRANCH_NAME=specialize
   Results will be posted here when complete
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "alamb-ghbot (via GitHub)" <gi...@apache.org>.
alamb-ghbot commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3638413293

   🤖: Benchmark completed
   
   <details><summary>Details</summary>
   <p>
   
   
   ```
   group                                          main                                   specialize
   -----                                          ----                                   ----------
   in_list/Float32/list=100/nulls=0%              1.01    305.6±1.35µs        ? ?/sec    1.00    303.3±1.81µs        ? ?/sec
   in_list/Float32/list=100/nulls=20%             1.09   392.5±12.14µs        ? ?/sec    1.00    358.9±2.98µs        ? ?/sec
   in_list/Float32/list=3/nulls=0%                1.03     14.7±0.65µs        ? ?/sec    1.00     14.3±0.52µs        ? ?/sec
   in_list/Float32/list=3/nulls=20%               1.05     19.7±0.62µs        ? ?/sec    1.00     18.8±0.24µs        ? ?/sec
   in_list/Float32/list=8/nulls=0%                1.00     29.0±0.11µs        ? ?/sec    1.02     29.6±0.96µs        ? ?/sec
   in_list/Float32/list=8/nulls=20%               1.11     39.2±0.35µs        ? ?/sec    1.00     35.4±0.24µs        ? ?/sec
   in_list/Int32/list=100/nulls=0%                1.17      6.0±0.16µs        ? ?/sec    1.00      5.2±0.19µs        ? ?/sec
   in_list/Int32/list=100/nulls=20%               1.79      8.4±0.14µs        ? ?/sec    1.00      4.7±0.15µs        ? ?/sec
   in_list/Int32/list=3/nulls=0%                  1.44      5.7±0.09µs        ? ?/sec    1.00      3.9±0.12µs        ? ?/sec
   in_list/Int32/list=3/nulls=20%                 2.17      8.6±0.19µs        ? ?/sec    1.00      4.0±0.05µs        ? ?/sec
   in_list/Int32/list=8/nulls=0%                  1.43      6.0±0.16µs        ? ?/sec    1.00      4.2±0.02µs        ? ?/sec
   in_list/Int32/list=8/nulls=20%                 1.94      8.8±0.31µs        ? ?/sec    1.00      4.5±0.16µs        ? ?/sec
   in_list/Utf8/list=100/nulls=0%/str=100         1.01   655.6±13.76µs        ? ?/sec    1.00    647.4±7.72µs        ? ?/sec
   in_list/Utf8/list=100/nulls=0%/str=12          1.03   682.9±10.42µs        ? ?/sec    1.00    664.6±8.23µs        ? ?/sec
   in_list/Utf8/list=100/nulls=0%/str=3           1.00    667.5±2.10µs        ? ?/sec    1.00    669.9±9.19µs        ? ?/sec
   in_list/Utf8/list=100/nulls=20%/str=100        1.00    594.5±2.21µs        ? ?/sec    1.02    606.1±4.71µs        ? ?/sec
   in_list/Utf8/list=100/nulls=20%/str=12         1.00    617.0±3.86µs        ? ?/sec    1.00    615.1±2.64µs        ? ?/sec
   in_list/Utf8/list=100/nulls=20%/str=3          1.03    633.6±7.70µs        ? ?/sec    1.00    617.9±5.61µs        ? ?/sec
   in_list/Utf8/list=3/nulls=0%/str=100           1.00     25.5±0.18µs        ? ?/sec    1.04     26.5±0.60µs        ? ?/sec
   in_list/Utf8/list=3/nulls=0%/str=12            1.03     26.7±0.79µs        ? ?/sec    1.00     25.9±0.30µs        ? ?/sec
   in_list/Utf8/list=3/nulls=0%/str=3             1.00     27.3±0.14µs        ? ?/sec    1.00     27.4±0.61µs        ? ?/sec
   in_list/Utf8/list=3/nulls=20%/str=100          1.01     26.0±0.35µs        ? ?/sec    1.00     25.8±0.79µs        ? ?/sec
   in_list/Utf8/list=3/nulls=20%/str=12           1.00     27.0±0.59µs        ? ?/sec    1.01     27.2±0.12µs        ? ?/sec
   in_list/Utf8/list=3/nulls=20%/str=3            1.03     26.7±0.54µs        ? ?/sec    1.00     26.0±0.28µs        ? ?/sec
   in_list/Utf8/list=8/nulls=0%/str=100           1.02     56.1±1.55µs        ? ?/sec    1.00     54.9±0.34µs        ? ?/sec
   in_list/Utf8/list=8/nulls=0%/str=12            1.00     55.9±0.30µs        ? ?/sec    1.00     55.6±0.40µs        ? ?/sec
   in_list/Utf8/list=8/nulls=0%/str=3             1.00     55.1±0.24µs        ? ?/sec    1.08     59.4±2.05µs        ? ?/sec
   in_list/Utf8/list=8/nulls=20%/str=100          1.01     52.5±1.17µs        ? ?/sec    1.00     52.2±0.50µs        ? ?/sec
   in_list/Utf8/list=8/nulls=20%/str=12           1.00     54.1±1.20µs        ? ?/sec    1.00     53.8±0.28µs        ? ?/sec
   in_list/Utf8/list=8/nulls=20%/str=3            1.02     54.3±1.53µs        ? ?/sec    1.00     53.2±0.51µs        ? ?/sec
   in_list/Utf8View/list=100/nulls=0%/str=100     1.00    595.6±6.39µs        ? ?/sec    1.05    622.7±4.73µs        ? ?/sec
   in_list/Utf8View/list=100/nulls=0%/str=12      1.00    578.3±6.18µs        ? ?/sec    1.00    576.7±5.17µs        ? ?/sec
   in_list/Utf8View/list=100/nulls=0%/str=3       1.00    577.9±4.87µs        ? ?/sec    1.00    575.4±3.80µs        ? ?/sec
   in_list/Utf8View/list=100/nulls=20%/str=100    1.00   505.1±10.14µs        ? ?/sec    1.04    527.3±1.63µs        ? ?/sec
   in_list/Utf8View/list=100/nulls=20%/str=12     1.00    509.6±2.37µs        ? ?/sec    1.00    511.4±6.18µs        ? ?/sec
   in_list/Utf8View/list=100/nulls=20%/str=3      1.00   516.3±16.20µs        ? ?/sec    1.00    516.9±7.63µs        ? ?/sec
   in_list/Utf8View/list=3/nulls=0%/str=100       1.05     22.2±0.41µs        ? ?/sec    1.00     21.2±0.33µs        ? ?/sec
   in_list/Utf8View/list=3/nulls=0%/str=12        1.07     23.6±0.47µs        ? ?/sec    1.00     22.2±0.16µs        ? ?/sec
   in_list/Utf8View/list=3/nulls=0%/str=3         1.04     23.2±0.14µs        ? ?/sec    1.00     22.2±0.21µs        ? ?/sec
   in_list/Utf8View/list=3/nulls=20%/str=100      1.00     22.8±0.15µs        ? ?/sec    1.00     22.8±0.49µs        ? ?/sec
   in_list/Utf8View/list=3/nulls=20%/str=12       1.03     23.8±1.22µs        ? ?/sec    1.00     23.0±0.29µs        ? ?/sec
   in_list/Utf8View/list=3/nulls=20%/str=3        1.01     23.4±0.12µs        ? ?/sec    1.00     23.1±0.40µs        ? ?/sec
   in_list/Utf8View/list=8/nulls=0%/str=100       1.00     48.8±0.38µs        ? ?/sec    1.01     49.5±1.38µs        ? ?/sec
   in_list/Utf8View/list=8/nulls=0%/str=12        1.23     61.1±0.51µs        ? ?/sec    1.00     49.7±0.61µs        ? ?/sec
   in_list/Utf8View/list=8/nulls=0%/str=3         1.23     61.2±0.36µs        ? ?/sec    1.00     49.8±0.62µs        ? ?/sec
   in_list/Utf8View/list=8/nulls=20%/str=100      1.00     44.9±0.93µs        ? ?/sec    1.02     45.7±0.34µs        ? ?/sec
   in_list/Utf8View/list=8/nulls=20%/str=12       1.03     47.5±0.91µs        ? ?/sec    1.00     46.3±2.34µs        ? ?/sec
   in_list/Utf8View/list=8/nulls=20%/str=3        1.03     49.4±0.27µs        ? ?/sec    1.00     48.0±1.63µs        ? ?/sec
   ```
   
   
   </p>
   </details>
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#discussion_r2597474781


##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,68 +211,127 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
-    null_count: usize,
-    values: HashSet<i32>,
-}
+// Macro to generate specialized StaticFilter implementations for primitive types
+macro_rules! primitive_static_filter {
+    ($Name:ident, $ArrowType:ty) => {
+        struct $Name {
+            null_count: usize,
+            values: HashSet<<$ArrowType as ArrowPrimitiveType>::Native>,
+        }
 
-impl Int32StaticFilter {
-    fn try_new(in_array: &ArrayRef) -> Result<Self> {
-        let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+        impl $Name {
+            fn try_new(in_array: &ArrayRef) -> Result<Self> {
+                let in_array = in_array
+                    .as_primitive_opt::<$ArrowType>()
+                    .ok_or_else(|| exec_datafusion_err!("Failed to downcast an array to a '{}' array", stringify!($ArrowType)))?;
 
-        let mut values = HashSet::with_capacity(in_array.len());
-        let null_count = in_array.null_count();
+                let mut values = HashSet::with_capacity(in_array.len());
+                let null_count = in_array.null_count();
+
+                for v in in_array.iter().flatten() {
+                    values.insert(v);
+                }
 
-        for v in in_array.iter().flatten() {
-            values.insert(v);
+                Ok(Self { null_count, values })
+            }
         }
 
-        Ok(Self { null_count, values })
-    }
-}
+        impl StaticFilter for $Name {
+            fn null_count(&self) -> usize {
+                self.null_count
+            }
 
-impl StaticFilter for Int32StaticFilter {
-    fn null_count(&self) -> usize {
-        self.null_count
-    }
+            fn contains(&self, v: &dyn Array, negated: bool) -> Result<BooleanArray> {
+                // Handle dictionary arrays by recursing on the values
+                downcast_dictionary_array! {
+                    v => {
+                        let values_contains = self.contains(v.values().as_ref(), negated)?;
+                        let result = take(&values_contains, v.keys(), None)?;
+                        return Ok(downcast_array(result.as_ref()))
+                    }
+                    _ => {}
+                }
 
-    fn contains(&self, v: &dyn Array, negated: bool) -> Result<BooleanArray> {
-        let v = v
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
-
-        let result = match (v.null_count() > 0, negated) {
-            (true, false) => {
-                // has nulls, not negated"
-                BooleanArray::from_iter(
-                    v.iter().map(|value| Some(self.values.contains(&value?))),
-                )
-            }
-            (true, true) => {
-                // has nulls, negated
-                BooleanArray::from_iter(
-                    v.iter().map(|value| Some(!self.values.contains(&value?))),
-                )
-            }
-            (false, false) => {
-                //no null, not negated
-                BooleanArray::from_iter(
-                    v.values().iter().map(|value| self.values.contains(value)),
-                )
-            }
-            (false, true) => {
-                // no null, negated
-                BooleanArray::from_iter(
-                    v.values().iter().map(|value| !self.values.contains(value)),
-                )
+                let v = v
+                    .as_primitive_opt::<$ArrowType>()
+                    .ok_or_else(|| exec_datafusion_err!("Failed to downcast an array to a '{}' array", stringify!($ArrowType)))?;
+
+                let haystack_has_nulls = self.null_count > 0;
+
+                let result = match (v.null_count() > 0, haystack_has_nulls, negated) {
+                    (true, _, false) | (false, true, false) => {

Review Comment:
   You can simplify this slightly complex 6 boolean match with:
   ```rust
   let has_nulls = v.null_count() > 0 || haystack_has_nulls;
   match (has_nulls, negated) {
       (true, false) => { /* Either needle or haystack has nulls, not negated */ }
       (true, true) => { /* Either needle or haystack has nulls, negated */ }
       (false, false) => { /* no nulls anywhere, not negated */ }
       (false, true) => { /* no nulls anywhere, negated */ }
   }
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on code in PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#discussion_r2603405458


##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,65 +248,414 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
-    null_count: usize,
-    values: HashSet<i32>,
+/// Threshold for switching from sorted Vec (binary search) to HashSet
+/// For small lists, binary search has better cache locality and lower overhead
+/// Maximum list size for using sorted lookup (binary search).
+/// Lists with more elements use hash lookup instead.
+const SORTED_LOOKUP_MAX_LEN: usize = 8;
+
+/// Helper to build a BooleanArray result for IN list operations.
+/// Handles SQL three-valued logic for NULL values.
+///
+/// # Arguments
+/// * `len` - Number of elements in the needle array
+/// * `needle_nulls` - Optional validity buffer from the needle array
+/// * `haystack_has_nulls` - Whether the IN list contains NULL values
+/// * `negated` - Whether this is a NOT IN operation
+/// * `contains` - Closure that returns whether needle[i] is found in the haystack
+#[inline]
+fn build_in_list_result<C>(
+    len: usize,
+    needle_nulls: Option<&NullBuffer>,
+    haystack_has_nulls: bool,
+    negated: bool,
+    contains: C,
+) -> BooleanArray
+where
+    C: Fn(usize) -> bool,
+{
+    // Use collect_bool for all paths - it's vectorized and faster than element-by-element append.
+    // Match on (needle_has_nulls, haystack_has_nulls, negated) to specialize each case.
+    match (needle_nulls, haystack_has_nulls, negated) {
+        // Haystack has nulls: result is NULL when not found (might match the NULL)
+        // values_buf == nulls_buf, so compute once and clone
+        (Some(validity), true, false) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let buf = validity.inner() & &contains_buf;
+            BooleanArray::new(buf.clone(), Some(NullBuffer::new(buf)))
+        }
+        (None, true, false) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            BooleanArray::new(buf.clone(), Some(NullBuffer::new(buf)))
+        }
+        (Some(validity), true, true) => {
+            // Compute nulls_buf via SIMD AND, then derive values_buf via XOR.
+            // Uses identity: A & !B = A ^ (A & B) to get values from nulls.
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let nulls_buf = validity.inner() & &contains_buf;
+            let values_buf = validity.inner() ^ &nulls_buf; // valid & !contains
+            BooleanArray::new(values_buf, Some(NullBuffer::new(nulls_buf)))
+        }
+        (None, true, true) => {
+            // No needle nulls, but haystack has nulls
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = !&contains_buf;
+            BooleanArray::new(values_buf, Some(NullBuffer::new(contains_buf)))
+        }
+        // Only needle has nulls: nulls_buf is just validity (reuse it directly!)
+        (Some(validity), false, false) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = validity.inner() & &contains_buf;
+            BooleanArray::new(values_buf, Some(validity.clone()))
+        }
+        (Some(validity), false, true) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = validity.inner() & &(!&contains_buf);
+            BooleanArray::new(values_buf, Some(validity.clone()))
+        }
+        // No nulls anywhere: no validity buffer needed
+        (None, false, false) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            BooleanArray::new(buf, None)
+        }
+        (None, false, true) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| !contains(i));
+            BooleanArray::new(buf, None)
+        }
+    }
 }
 
-impl Int32StaticFilter {
-    fn try_new(in_array: &ArrayRef) -> Result<Self> {
-        let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+/// Sorted lookup using binary search. Best for small lists (< 8 elements).
+struct SortedLookup<T>(Vec<T>);
 
-        let mut values = HashSet::with_capacity(in_array.len());
-        let null_count = in_array.null_count();
+impl<T: Ord> SortedLookup<T> {
+    fn new(mut values: Vec<T>) -> Self {
+        values.sort_unstable();
+        values.dedup();
+        Self(values)
+    }
 
-        for v in in_array.iter().flatten() {
-            values.insert(v);
-        }
+    #[inline]
+    fn contains(&self, value: &T) -> bool {
+        self.0.binary_search(value).is_ok()

Review Comment:
   Yes I think we need to freeze this (and maybe even split it up). Since you have some great ideas and can execute them I would love it you could open an issue tracking the "plan" and then we can make smaller targeted PRs off of that. I personally have *a lot* of other DataFusion work on my plate so I'd love to hand off a bit of this to those with better ideas and more interest and I can then help review PRs, etc?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on code in PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#discussion_r2603408088


##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,65 +248,414 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
-    null_count: usize,
-    values: HashSet<i32>,
+/// Threshold for switching from sorted Vec (binary search) to HashSet
+/// For small lists, binary search has better cache locality and lower overhead
+/// Maximum list size for using sorted lookup (binary search).
+/// Lists with more elements use hash lookup instead.
+const SORTED_LOOKUP_MAX_LEN: usize = 8;
+
+/// Helper to build a BooleanArray result for IN list operations.
+/// Handles SQL three-valued logic for NULL values.
+///
+/// # Arguments
+/// * `len` - Number of elements in the needle array
+/// * `needle_nulls` - Optional validity buffer from the needle array
+/// * `haystack_has_nulls` - Whether the IN list contains NULL values
+/// * `negated` - Whether this is a NOT IN operation
+/// * `contains` - Closure that returns whether needle[i] is found in the haystack
+#[inline]
+fn build_in_list_result<C>(
+    len: usize,
+    needle_nulls: Option<&NullBuffer>,
+    haystack_has_nulls: bool,
+    negated: bool,
+    contains: C,
+) -> BooleanArray
+where
+    C: Fn(usize) -> bool,
+{
+    // Use collect_bool for all paths - it's vectorized and faster than element-by-element append.
+    // Match on (needle_has_nulls, haystack_has_nulls, negated) to specialize each case.
+    match (needle_nulls, haystack_has_nulls, negated) {
+        // Haystack has nulls: result is NULL when not found (might match the NULL)
+        // values_buf == nulls_buf, so compute once and clone
+        (Some(validity), true, false) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let buf = validity.inner() & &contains_buf;
+            BooleanArray::new(buf.clone(), Some(NullBuffer::new(buf)))
+        }
+        (None, true, false) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            BooleanArray::new(buf.clone(), Some(NullBuffer::new(buf)))
+        }
+        (Some(validity), true, true) => {
+            // Compute nulls_buf via SIMD AND, then derive values_buf via XOR.
+            // Uses identity: A & !B = A ^ (A & B) to get values from nulls.
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let nulls_buf = validity.inner() & &contains_buf;
+            let values_buf = validity.inner() ^ &nulls_buf; // valid & !contains
+            BooleanArray::new(values_buf, Some(NullBuffer::new(nulls_buf)))
+        }
+        (None, true, true) => {
+            // No needle nulls, but haystack has nulls
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = !&contains_buf;
+            BooleanArray::new(values_buf, Some(NullBuffer::new(contains_buf)))
+        }
+        // Only needle has nulls: nulls_buf is just validity (reuse it directly!)
+        (Some(validity), false, false) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = validity.inner() & &contains_buf;
+            BooleanArray::new(values_buf, Some(validity.clone()))
+        }
+        (Some(validity), false, true) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = validity.inner() & &(!&contains_buf);
+            BooleanArray::new(values_buf, Some(validity.clone()))
+        }
+        // No nulls anywhere: no validity buffer needed
+        (None, false, false) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            BooleanArray::new(buf, None)
+        }
+        (None, false, true) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| !contains(i));
+            BooleanArray::new(buf, None)
+        }
+    }
 }
 
-impl Int32StaticFilter {
-    fn try_new(in_array: &ArrayRef) -> Result<Self> {
-        let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+/// Sorted lookup using binary search. Best for small lists (< 8 elements).
+struct SortedLookup<T>(Vec<T>);
 
-        let mut values = HashSet::with_capacity(in_array.len());
-        let null_count = in_array.null_count();
+impl<T: Ord> SortedLookup<T> {
+    fn new(mut values: Vec<T>) -> Self {
+        values.sort_unstable();
+        values.dedup();
+        Self(values)
+    }
 
-        for v in in_array.iter().flatten() {
-            values.insert(v);
-        }
+    #[inline]
+    fn contains(&self, value: &T) -> bool {
+        self.0.binary_search(value).is_ok()

Review Comment:
   > AI coding agents are really super useful for quickly bringing crazy ideas to life, I'm a big fan of our current timeline 😄
   
   Poor @alamb 😭 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3634544687

   (I fixed the script to support 
   
   > The key is `benchmark` vs `benchmarks` fyi. I can make a PR to accept both tomorrow.
   
   Yeah, I thought I could bash it out quickly but sadly it took more than 30 seconds


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#discussion_r2603365909


##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,65 +248,414 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
-    null_count: usize,
-    values: HashSet<i32>,
+/// Threshold for switching from sorted Vec (binary search) to HashSet
+/// For small lists, binary search has better cache locality and lower overhead
+/// Maximum list size for using sorted lookup (binary search).
+/// Lists with more elements use hash lookup instead.
+const SORTED_LOOKUP_MAX_LEN: usize = 8;
+
+/// Helper to build a BooleanArray result for IN list operations.
+/// Handles SQL three-valued logic for NULL values.
+///
+/// # Arguments
+/// * `len` - Number of elements in the needle array
+/// * `needle_nulls` - Optional validity buffer from the needle array
+/// * `haystack_has_nulls` - Whether the IN list contains NULL values
+/// * `negated` - Whether this is a NOT IN operation
+/// * `contains` - Closure that returns whether needle[i] is found in the haystack
+#[inline]
+fn build_in_list_result<C>(
+    len: usize,
+    needle_nulls: Option<&NullBuffer>,
+    haystack_has_nulls: bool,
+    negated: bool,
+    contains: C,
+) -> BooleanArray
+where
+    C: Fn(usize) -> bool,
+{
+    // Use collect_bool for all paths - it's vectorized and faster than element-by-element append.
+    // Match on (needle_has_nulls, haystack_has_nulls, negated) to specialize each case.
+    match (needle_nulls, haystack_has_nulls, negated) {
+        // Haystack has nulls: result is NULL when not found (might match the NULL)
+        // values_buf == nulls_buf, so compute once and clone
+        (Some(validity), true, false) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let buf = validity.inner() & &contains_buf;
+            BooleanArray::new(buf.clone(), Some(NullBuffer::new(buf)))
+        }
+        (None, true, false) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            BooleanArray::new(buf.clone(), Some(NullBuffer::new(buf)))
+        }
+        (Some(validity), true, true) => {
+            // Compute nulls_buf via SIMD AND, then derive values_buf via XOR.
+            // Uses identity: A & !B = A ^ (A & B) to get values from nulls.
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let nulls_buf = validity.inner() & &contains_buf;
+            let values_buf = validity.inner() ^ &nulls_buf; // valid & !contains
+            BooleanArray::new(values_buf, Some(NullBuffer::new(nulls_buf)))
+        }
+        (None, true, true) => {
+            // No needle nulls, but haystack has nulls
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = !&contains_buf;
+            BooleanArray::new(values_buf, Some(NullBuffer::new(contains_buf)))
+        }
+        // Only needle has nulls: nulls_buf is just validity (reuse it directly!)
+        (Some(validity), false, false) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = validity.inner() & &contains_buf;
+            BooleanArray::new(values_buf, Some(validity.clone()))
+        }
+        (Some(validity), false, true) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = validity.inner() & &(!&contains_buf);
+            BooleanArray::new(values_buf, Some(validity.clone()))
+        }
+        // No nulls anywhere: no validity buffer needed
+        (None, false, false) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            BooleanArray::new(buf, None)
+        }
+        (None, false, true) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| !contains(i));
+            BooleanArray::new(buf, None)
+        }
+    }
 }
 
-impl Int32StaticFilter {
-    fn try_new(in_array: &ArrayRef) -> Result<Self> {
-        let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+/// Sorted lookup using binary search. Best for small lists (< 8 elements).
+struct SortedLookup<T>(Vec<T>);
 
-        let mut values = HashSet::with_capacity(in_array.len());
-        let null_count = in_array.null_count();
+impl<T: Ord> SortedLookup<T> {
+    fn new(mut values: Vec<T>) -> Self {
+        values.sort_unstable();
+        values.dedup();
+        Self(values)
+    }
 
-        for v in in_array.iter().flatten() {
-            values.insert(v);
-        }
+    #[inline]
+    fn contains(&self, value: &T) -> bool {
+        self.0.binary_search(value).is_ok()

Review Comment:
   @Dandandan and @adriangb: I opened a PR to `pydantic` at https://github.com/pydantic/datafusion/pull/48 as a POC with the bench numbers on my mac.
   
   It shows another ~70% improvement on short in-lists of primitive types, and ~40% on short utf8view in-lists as well.
   
   This is a pretty major refactor, so I'm very much in favor of "freezing" the features of this PR and leaving my further improvement to later!
   
   AI coding agents are really super useful for quickly bringing crazy ideas to life, I'm a big fan of our current timeline 😄 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#discussion_r2603433605


##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,65 +248,414 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
-    null_count: usize,
-    values: HashSet<i32>,
+/// Threshold for switching from sorted Vec (binary search) to HashSet
+/// For small lists, binary search has better cache locality and lower overhead
+/// Maximum list size for using sorted lookup (binary search).
+/// Lists with more elements use hash lookup instead.
+const SORTED_LOOKUP_MAX_LEN: usize = 8;
+
+/// Helper to build a BooleanArray result for IN list operations.
+/// Handles SQL three-valued logic for NULL values.
+///
+/// # Arguments
+/// * `len` - Number of elements in the needle array
+/// * `needle_nulls` - Optional validity buffer from the needle array
+/// * `haystack_has_nulls` - Whether the IN list contains NULL values
+/// * `negated` - Whether this is a NOT IN operation
+/// * `contains` - Closure that returns whether needle[i] is found in the haystack
+#[inline]
+fn build_in_list_result<C>(
+    len: usize,
+    needle_nulls: Option<&NullBuffer>,
+    haystack_has_nulls: bool,
+    negated: bool,
+    contains: C,
+) -> BooleanArray
+where
+    C: Fn(usize) -> bool,
+{
+    // Use collect_bool for all paths - it's vectorized and faster than element-by-element append.
+    // Match on (needle_has_nulls, haystack_has_nulls, negated) to specialize each case.
+    match (needle_nulls, haystack_has_nulls, negated) {
+        // Haystack has nulls: result is NULL when not found (might match the NULL)
+        // values_buf == nulls_buf, so compute once and clone
+        (Some(validity), true, false) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let buf = validity.inner() & &contains_buf;
+            BooleanArray::new(buf.clone(), Some(NullBuffer::new(buf)))
+        }
+        (None, true, false) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            BooleanArray::new(buf.clone(), Some(NullBuffer::new(buf)))
+        }
+        (Some(validity), true, true) => {
+            // Compute nulls_buf via SIMD AND, then derive values_buf via XOR.
+            // Uses identity: A & !B = A ^ (A & B) to get values from nulls.
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let nulls_buf = validity.inner() & &contains_buf;
+            let values_buf = validity.inner() ^ &nulls_buf; // valid & !contains
+            BooleanArray::new(values_buf, Some(NullBuffer::new(nulls_buf)))
+        }
+        (None, true, true) => {
+            // No needle nulls, but haystack has nulls
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = !&contains_buf;
+            BooleanArray::new(values_buf, Some(NullBuffer::new(contains_buf)))
+        }
+        // Only needle has nulls: nulls_buf is just validity (reuse it directly!)
+        (Some(validity), false, false) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = validity.inner() & &contains_buf;
+            BooleanArray::new(values_buf, Some(validity.clone()))
+        }
+        (Some(validity), false, true) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = validity.inner() & &(!&contains_buf);
+            BooleanArray::new(values_buf, Some(validity.clone()))
+        }
+        // No nulls anywhere: no validity buffer needed
+        (None, false, false) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            BooleanArray::new(buf, None)
+        }
+        (None, false, true) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| !contains(i));
+            BooleanArray::new(buf, None)
+        }
+    }
 }
 
-impl Int32StaticFilter {
-    fn try_new(in_array: &ArrayRef) -> Result<Self> {
-        let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+/// Sorted lookup using binary search. Best for small lists (< 8 elements).
+struct SortedLookup<T>(Vec<T>);
 
-        let mut values = HashSet::with_capacity(in_array.len());
-        let null_count = in_array.null_count();
+impl<T: Ord> SortedLookup<T> {
+    fn new(mut values: Vec<T>) -> Self {
+        values.sort_unstable();
+        values.dedup();
+        Self(values)
+    }
 
-        for v in in_array.iter().flatten() {
-            values.insert(v);
-        }
+    #[inline]
+    fn contains(&self, value: &T) -> bool {
+        self.0.binary_search(value).is_ok()

Review Comment:
   > smaller targeted PRs off of that
   
   That's definitely the way to go! I'll fork off an issue from https://github.com/apache/datafusion/issues/18824.
   
   EDIT: see https://github.com/apache/datafusion/issues/19241



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3638293170

   run benchmark in_list


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "alamb-ghbot (via GitHub)" <gi...@apache.org>.
alamb-ghbot commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3643396121

   🤖 `./gh_compare_branch_bench.sh` [compare_branch_bench.sh](https://github.com/alamb/datafusion-benchmarking/blob/main/scripts/compare_branch_bench.sh) Running
   Linux aal-dev 6.14.0-1018-gcp #19~24.04.1-Ubuntu SMP Wed Sep 24 23:23:09 UTC 2025 x86_64 x86_64 x86_64 GNU/Linux
   Comparing specialize (b6404e5bcd119782d08853095c1bd7f9943d5893) to e8a0829b7a2044ab477784d60ed2d208b97f5042 [diff](https://github.com/apache/datafusion/compare/e8a0829b7a2044ab477784d60ed2d208b97f5042..b6404e5bcd119782d08853095c1bd7f9943d5893)
   BENCH_NAME=in_list
   BENCH_COMMAND=cargo bench --all-features --bench in_list
   BENCH_FILTER=
   BENCH_BRANCH_NAME=specialize
   Results will be posted here when complete
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3643395652

   run benchmark in_list


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "alamb-ghbot (via GitHub)" <gi...@apache.org>.
alamb-ghbot commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3634443002

   🤖 Hi @adriangb, thanks for the request (https://github.com/apache/datafusion/pull/18832#issuecomment-3634442805).
   
   [`scrape_comments.py`](https://github.com/alamb/datafusion-benchmarking/blob/main/scripts/scrape_comments.py) only supports whitelisted benchmarks.
   - Standard: clickbench_1, clickbench_extended, clickbench_partitioned, clickbench_pushdown, tpch, tpch10, tpch_mem, tpch_mem10
   - Criterion: aggregate_query_sql, aggregate_vectorized, case_when, in_list, sql_planner
   
   Please choose one or more of these with `run benchmark <name>` or `run benchmark <name1> <name2>...`


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3643581726

   > The benchmarks are now looking *very* good, and this has gone through several rounds of review, all of it addressed. But there are significant changes since the last approvals. @geoffreyclaude could you give another review and approve if you think it's ready so we can merge this piece and continue work in https://github.com/apache/datafusion/issues/19241
   
   The tests you added as a dedicated PR give a lot of confidence this isn't introducing any functional regression. And perf-wise, then benchmarks speak for themselves!
   
   Do we have more generic benches that exercise this path? Maybe the Clickbench ones? Would be nice to see the big picture and make sure this isn't "benchmaxing" with unexpected adverse effects in real life.
   
   Otherwise, ✅ from me of course. You addressed my remaining two nits already.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb merged PR #18832:
URL: https://github.com/apache/datafusion/pull/18832


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3566646830

   🤖: Benchmark completed
   
   <details><summary>Details</summary>
   <p>
   
   
   ```
   Comparing HEAD and specialize
   --------------------
   Benchmark clickbench_extended.json
   --------------------
   ┏━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┓
   ┃ Query        ┃        HEAD ┃  specialize ┃       Change ┃
   ┡━━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━━━━━━━┩
   │ QQuery 0     │  2653.29 ms │  2643.63 ms │    no change │
   │ QQuery 1     │  1306.60 ms │  1281.59 ms │    no change │
   │ QQuery 2     │  2455.20 ms │  2370.32 ms │    no change │
   │ QQuery 3     │  1156.08 ms │  1114.79 ms │    no change │
   │ QQuery 4     │  2330.46 ms │  2304.88 ms │    no change │
   │ QQuery 5     │ 28126.46 ms │ 28010.99 ms │    no change │
   │ QQuery 6     │  4067.69 ms │  4060.48 ms │    no change │
   │ QQuery 7     │  3638.82 ms │  3851.00 ms │ 1.06x slower │
   └──────────────┴─────────────┴─────────────┴──────────────┘
   ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━┓
   ┃ Benchmark Summary         ┃            ┃
   ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━┩
   │ Total Time (HEAD)         │ 45734.60ms │
   │ Total Time (specialize)   │ 45637.68ms │
   │ Average Time (HEAD)       │  5716.82ms │
   │ Average Time (specialize) │  5704.71ms │
   │ Queries Faster            │          0 │
   │ Queries Slower            │          1 │
   │ Queries with No Change    │          7 │
   │ Queries with Failure      │          0 │
   └───────────────────────────┴────────────┘
   --------------------
   Benchmark clickbench_partitioned.json
   --------------------
   ┏━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓
   ┃ Query        ┃        HEAD ┃  specialize ┃        Change ┃
   ┡━━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩
   │ QQuery 0     │     2.51 ms │     2.23 ms │ +1.13x faster │
   │ QQuery 1     │    51.64 ms │    50.17 ms │     no change │
   │ QQuery 2     │   136.71 ms │   138.99 ms │     no change │
   │ QQuery 3     │   164.21 ms │   165.13 ms │     no change │
   │ QQuery 4     │  1070.98 ms │  1088.91 ms │     no change │
   │ QQuery 5     │  1510.36 ms │  1485.90 ms │     no change │
   │ QQuery 6     │     2.17 ms │     2.20 ms │     no change │
   │ QQuery 7     │    55.51 ms │    55.89 ms │     no change │
   │ QQuery 8     │  1426.35 ms │  1446.26 ms │     no change │
   │ QQuery 9     │  1872.18 ms │  1829.87 ms │     no change │
   │ QQuery 10    │   380.85 ms │   367.57 ms │     no change │
   │ QQuery 11    │   458.71 ms │   417.23 ms │ +1.10x faster │
   │ QQuery 12    │  1408.78 ms │  1382.73 ms │     no change │
   │ QQuery 13    │  2081.78 ms │  2148.16 ms │     no change │
   │ QQuery 14    │  1242.39 ms │  1286.95 ms │     no change │
   │ QQuery 15    │  1216.37 ms │  1262.77 ms │     no change │
   │ QQuery 16    │  2679.04 ms │  2730.67 ms │     no change │
   │ QQuery 17    │  2657.52 ms │  2666.04 ms │     no change │
   │ QQuery 18    │  5347.62 ms │  4996.68 ms │ +1.07x faster │
   │ QQuery 19    │   129.19 ms │   126.78 ms │     no change │
   │ QQuery 20    │  2020.18 ms │  1974.03 ms │     no change │
   │ QQuery 21    │  2330.14 ms │  2291.15 ms │     no change │
   │ QQuery 22    │  3990.08 ms │  3921.02 ms │     no change │
   │ QQuery 23    │ 12864.85 ms │ 12678.44 ms │     no change │
   │ QQuery 24    │   214.91 ms │   197.85 ms │ +1.09x faster │
   │ QQuery 25    │   477.06 ms │   465.64 ms │     no change │
   │ QQuery 26    │   221.72 ms │   211.14 ms │     no change │
   │ QQuery 27    │  2818.62 ms │  2800.08 ms │     no change │
   │ QQuery 28    │ 23386.04 ms │ 24032.36 ms │     no change │
   │ QQuery 29    │   963.31 ms │   964.57 ms │     no change │
   │ QQuery 30    │  1318.41 ms │  1329.87 ms │     no change │
   │ QQuery 31    │  1378.81 ms │  1352.16 ms │     no change │
   │ QQuery 32    │  4881.46 ms │  5040.19 ms │     no change │
   │ QQuery 33    │  5905.32 ms │  5981.60 ms │     no change │
   │ QQuery 34    │  6119.86 ms │  6348.76 ms │     no change │
   │ QQuery 35    │  1942.66 ms │  1904.86 ms │     no change │
   │ QQuery 36    │   120.95 ms │   120.81 ms │     no change │
   │ QQuery 37    │    52.95 ms │    53.06 ms │     no change │
   │ QQuery 38    │   121.94 ms │   120.66 ms │     no change │
   │ QQuery 39    │   196.99 ms │   198.57 ms │     no change │
   │ QQuery 40    │    43.90 ms │    41.87 ms │     no change │
   │ QQuery 41    │    39.75 ms │    37.46 ms │ +1.06x faster │
   │ QQuery 42    │    32.87 ms │    31.87 ms │     no change │
   └──────────────┴─────────────┴─────────────┴───────────────┘
   ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━┓
   ┃ Benchmark Summary         ┃            ┃
   ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━┩
   │ Total Time (HEAD)         │ 95337.65ms │
   │ Total Time (specialize)   │ 95749.15ms │
   │ Average Time (HEAD)       │  2217.15ms │
   │ Average Time (specialize) │  2226.72ms │
   │ Queries Faster            │          5 │
   │ Queries Slower            │          0 │
   │ Queries with No Change    │         38 │
   │ Queries with Failure      │          0 │
   └───────────────────────────┴────────────┘
   --------------------
   Benchmark tpch_mem_sf1.json
   --------------------
   ┏━━━━━━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓
   ┃ Query        ┃      HEAD ┃ specialize ┃        Change ┃
   ┡━━━━━━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩
   │ QQuery 1     │ 139.55 ms │  138.68 ms │     no change │
   │ QQuery 2     │  27.47 ms │   28.88 ms │  1.05x slower │
   │ QQuery 3     │  38.06 ms │   37.65 ms │     no change │
   │ QQuery 4     │  29.40 ms │   28.38 ms │     no change │
   │ QQuery 5     │  87.81 ms │   86.86 ms │     no change │
   │ QQuery 6     │  19.52 ms │   19.58 ms │     no change │
   │ QQuery 7     │ 222.64 ms │  227.15 ms │     no change │
   │ QQuery 8     │  34.19 ms │   35.26 ms │     no change │
   │ QQuery 9     │ 102.37 ms │  105.70 ms │     no change │
   │ QQuery 10    │  62.63 ms │   64.92 ms │     no change │
   │ QQuery 11    │  18.73 ms │   18.59 ms │     no change │
   │ QQuery 12    │  51.03 ms │   52.34 ms │     no change │
   │ QQuery 13    │  48.65 ms │   48.66 ms │     no change │
   │ QQuery 14    │  13.94 ms │   13.77 ms │     no change │
   │ QQuery 15    │  25.10 ms │   24.91 ms │     no change │
   │ QQuery 16    │  25.28 ms │   24.76 ms │     no change │
   │ QQuery 17    │ 153.69 ms │  150.64 ms │     no change │
   │ QQuery 18    │ 277.48 ms │  281.61 ms │     no change │
   │ QQuery 19    │  36.61 ms │   36.42 ms │     no change │
   │ QQuery 20    │  50.79 ms │   48.40 ms │     no change │
   │ QQuery 21    │ 338.03 ms │  318.12 ms │ +1.06x faster │
   │ QQuery 22    │  20.42 ms │   17.44 ms │ +1.17x faster │
   └──────────────┴───────────┴────────────┴───────────────┘
   ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━┓
   ┃ Benchmark Summary         ┃           ┃
   ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━┩
   │ Total Time (HEAD)         │ 1823.38ms │
   │ Total Time (specialize)   │ 1808.75ms │
   │ Average Time (HEAD)       │   82.88ms │
   │ Average Time (specialize) │   82.22ms │
   │ Queries Faster            │         2 │
   │ Queries Slower            │         1 │
   │ Queries with No Change    │        19 │
   │ Queries with Failure      │         0 │
   └───────────────────────────┴───────────┘
   ```
   
   
   </p>
   </details>
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "Dandandan (via GitHub)" <gi...@apache.org>.
Dandandan commented on code in PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#discussion_r2553808461


##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,68 +211,127 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
-    null_count: usize,
-    values: HashSet<i32>,
-}
+// Macro to generate specialized StaticFilter implementations for primitive types
+macro_rules! primitive_static_filter {
+    ($Name:ident, $ArrowType:ty) => {
+        struct $Name {
+            null_count: usize,
+            values: HashSet<<$ArrowType as ArrowPrimitiveType>::Native>,
+        }
 
-impl Int32StaticFilter {
-    fn try_new(in_array: &ArrayRef) -> Result<Self> {
-        let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+        impl $Name {
+            fn try_new(in_array: &ArrayRef) -> Result<Self> {
+                let in_array = in_array
+                    .as_primitive_opt::<$ArrowType>()
+                    .ok_or_else(|| exec_datafusion_err!("Failed to downcast an array to a '{}' array", stringify!($ArrowType)))?;
 
-        let mut values = HashSet::with_capacity(in_array.len());
-        let null_count = in_array.null_count();
+                let mut values = HashSet::with_capacity(in_array.len());
+                let null_count = in_array.null_count();
+
+                for v in in_array.iter().flatten() {
+                    values.insert(v);
+                }
 
-        for v in in_array.iter().flatten() {
-            values.insert(v);
+                Ok(Self { null_count, values })
+            }
         }
 
-        Ok(Self { null_count, values })
-    }
-}
+        impl StaticFilter for $Name {
+            fn null_count(&self) -> usize {
+                self.null_count
+            }
 
-impl StaticFilter for Int32StaticFilter {
-    fn null_count(&self) -> usize {
-        self.null_count
-    }
+            fn contains(&self, v: &dyn Array, negated: bool) -> Result<BooleanArray> {
+                // Handle dictionary arrays by recursing on the values
+                downcast_dictionary_array! {
+                    v => {
+                        let values_contains = self.contains(v.values().as_ref(), negated)?;
+                        let result = take(&values_contains, v.keys(), None)?;
+                        return Ok(downcast_array(result.as_ref()))
+                    }
+                    _ => {}
+                }
 
-    fn contains(&self, v: &dyn Array, negated: bool) -> Result<BooleanArray> {
-        let v = v
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
-
-        let result = match (v.null_count() > 0, negated) {
-            (true, false) => {
-                // has nulls, not negated"
-                BooleanArray::from_iter(
-                    v.iter().map(|value| Some(self.values.contains(&value?))),
-                )
-            }
-            (true, true) => {
-                // has nulls, negated
-                BooleanArray::from_iter(
-                    v.iter().map(|value| Some(!self.values.contains(&value?))),
-                )
-            }
-            (false, false) => {
-                //no null, not negated
-                BooleanArray::from_iter(
-                    v.values().iter().map(|value| self.values.contains(value)),
-                )
-            }
-            (false, true) => {
-                // no null, negated
-                BooleanArray::from_iter(
-                    v.values().iter().map(|value| !self.values.contains(value)),
-                )
+                let v = v
+                    .as_primitive_opt::<$ArrowType>()
+                    .ok_or_else(|| exec_datafusion_err!("Failed to downcast an array to a '{}' array", stringify!($ArrowType)))?;
+
+                let haystack_has_nulls = self.null_count > 0;
+
+                let result = match (v.null_count() > 0, haystack_has_nulls, negated) {
+                    (true, _, false) | (false, true, false) => {
+                        // Either needle or haystack has nulls, not negated
+                        BooleanArray::from_iter(v.iter().map(|value| {
+                            match value {
+                                // SQL three-valued logic: null IN (...) is always null
+                                None => None,
+                                Some(v) => {
+                                    if self.values.contains(&v) {
+                                        Some(true)
+                                    } else if haystack_has_nulls {
+                                        // value not in set, but set has nulls -> null
+                                        None
+                                    } else {
+                                        Some(false)
+                                    }
+                                }
+                            }
+                        }))
+                    }
+                    (true, _, true) | (false, true, true) => {
+                        // Either needle or haystack has nulls, negated
+                        BooleanArray::from_iter(v.iter().map(|value| {

Review Comment:
   It probably would be faster to handle the nulls separately or using `set_indices` rather than using `BooleanArray::from_iter` and `v.iter` etc.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3556437805

   Here's what I'm seeing so far:
   Function & State | main (us) | specialized (us) | Change
   -- | -- | -- | --
   in_list_utf8(5) (1024, 0) IN (1, 0) | 3.6205 | 4.8594 | Regressed (+34.239%)
   in_list_utf8(10) (1024, 0) IN (1, 0) | 3.6363 | 5.1001 | Regressed (+40.312%)
   in_list_utf8(20) (1024, 0) IN (1, 0) | 3.6707 | 4.9045 | Regressed (+33.600%)
   in_list_f32 (1024, 0) IN (1, 0) | 3.5255 | 3.2288 | Improved (−8.2971%)
   in_list_i32 (1024, 0) IN (1, 0) | 3.4923 | 3.6403 | Regressed (+3.8772%)
   in_list_utf8(5) (1024, 0.2) IN (1, 0) | 4.9284 | 6.3583 | Regressed (+29.002%)
   in_list_utf8(10) (1024, 0.2) IN (1, 0) | 4.9788 | 6.3273 | Regressed (+27.064%)
   in_list_utf8(20) (1024, 0.2) IN (1, 0) | 5.1145 | 6.4905 | Regressed (+26.907%)
   in_list_f32 (1024, 0.2) IN (1, 0) | 4.4894 | 4.2540 | Improved (−5.2512%)
   in_list_i32 (1024, 0.2) IN (1, 0) | 4.4055 | 4.2869 | Improved (−2.7526%)
   in_list_utf8(5) (1024, 0) IN (3, 0) | 3.5576 | 4.8733 | Regressed (+37.000%)
   in_list_utf8(10) (1024, 0) IN (3, 0) | 3.4999 | 4.8737 | Regressed (+37.108%)
   in_list_utf8(20) (1024, 0) IN (3, 0) | 3.4897 | 4.9039 | Regressed (+40.449%)
   in_list_f32 (1024, 0) IN (3, 0) | 3.5114 | 3.2550 | Improved (−7.3270%)
   in_list_i32 (1024, 0) IN (3, 0) | 3.5199 | 3.4879 | Noise Threshold (−0.9158%)
   in_list_utf8(5) (1024, 0.2) IN (3, 0) | 5.0196 | 6.2232 | Regressed (+23.865%)
   in_list_utf8(10) (1024, 0.2) IN (3, 0) | 5.0453 | 6.5280 | Regressed (+28.004%)
   in_list_utf8(20) (1024, 0.2) IN (3, 0) | 5.1005 | 11.124 | Regressed (+118.13%)
   in_list_f32 (1024, 0.2) IN (3, 0) | 4.5049 | 4.3126 | Improved (−4.6367%)
   in_list_i32 (1024, 0.2) IN (3, 0) | 4.4026 | 4.4424 | Noise Threshold (+1.0449%)
   in_list_utf8(5) (1024, 0) IN (10, 0) | 3.5275 | 4.9709 | Regressed (+40.969%)
   in_list_utf8(10) (1024, 0) IN (10, 0) | 3.5613 | 4.9125 | Regressed (+37.386%)
   in_list_utf8(20) (1024, 0) IN (10, 0) | 3.5589 | 4.8611 | Regressed (+36.578%)
   in_list_f32 (1024, 0) IN (10, 0) | 3.5596 | 3.2017 | Improved (−10.003%)
   in_list_i32 (1024, 0) IN (10, 0) | 3.4917 | 3.5190 | Noise Threshold (+1.0216%)
   in_list_utf8(5) (1024, 0.2) IN (10, 0) | 5.0368 | 6.6162 | Regressed (+31.725%)
   in_list_utf8(10) (1024, 0.2) IN (10, 0) | 5.0980 | 6.6660 | Regressed (+30.039%)
   in_list_utf8(20) (1024, 0.2) IN (10, 0) | 5.2543 | 6.5350 | Regressed (+24.335%)
   in_list_f32 (1024, 0.2) IN (10, 0) | 4.5609 | 4.3248 | Improved (−5.3746%)
   in_list_i32 (1024, 0.2) IN (10, 0) | 4.4460 | 4.3543 | Improved (−2.7754%)
   in_list_utf8(5) (1024, 0) IN (100, 0) | 3.6542 | 4.9992 | Regressed (+36.952%)
   in_list_utf8(10) (1024, 0) IN (100, 0) | 3.6529 | 4.8772 | Regressed (+33.560%)
   in_list_utf8(20) (1024, 0) IN (100, 0) | 3.6155 | 5.0250 | Regressed (+39.127%)
   in_list_f32 (1024, 0) IN (100, 0) | 3.6029 | 3.2448 | Improved (−9.7603%)
   in_list_i32 (1024, 0) IN (100, 0) | 3.6048 | 3.4770 | Improved (−3.5307%)
   in_list_utf8(5) (1024, 0.2) IN (100, 0) | 5.3988 | 6.6108 | Regressed (+22.866%)
   in_list_utf8(10) (1024, 0.2) IN (100, 0) | 5.4776 | 6.6567 | Regressed (+21.591%)
   in_list_utf8(20) (1024, 0.2) IN (100, 0) | 5.3721 | 6.6470 | Regressed (+24.058%)
   in_list_f32 (1024, 0.2) IN (100, 0) | 4.7693 | 4.3281 | Improved (−9.9814%)
   in_list_i32 (1024, 0.2) IN (100, 0) | 4.5402 | 4.4076 | Improved (−3.5247%)
   
   I think we'd need to add benchmarks for other primitive types.
   And it's interesting that Utf8 regresses a lot across the board. I guess the benefits of vectorization / computing the entire hashes at once outweighs the dynamic dispatch?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "martin-g (via GitHub)" <gi...@apache.org>.
martin-g commented on code in PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#discussion_r2546237709


##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -220,41 +347,63 @@ impl Int32StaticFilter {
     }
 }
 
-impl StaticFilter for Int32StaticFilter {
+impl StaticFilter for BooleanStaticFilter {
     fn null_count(&self) -> usize {
         self.null_count
     }
 
     fn contains(&self, v: &dyn Array, negated: bool) -> Result<BooleanArray> {
+        // Handle dictionary arrays by recursing on the values
+        downcast_dictionary_array! {
+            v => {
+                let values_contains = self.contains(v.values().as_ref(), negated)?;
+                let result = take(&values_contains, v.keys(), None)?;
+                return Ok(downcast_array(result.as_ref()))
+            }
+            _ => {}
+        }
+
         let v = v
-            .as_primitive_opt::<Int32Type>()
+            .as_boolean_opt()
             .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;

Review Comment:
   ```suggestion
               .ok_or_else(|| exec_datafusion_err!("Failed to downcast an array to a boolean array"))?;
   ```



##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,18 +208,135 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
+// Macro to generate specialized StaticFilter implementations for primitive types
+macro_rules! primitive_static_filter {
+    ($Name:ident, $ArrowType:ty) => {
+        struct $Name {
+            null_count: usize,
+            values: HashSet<<$ArrowType as ArrowPrimitiveType>::Native>,
+        }
+
+        impl $Name {
+            fn try_new(in_array: &ArrayRef) -> Result<Self> {
+                let in_array = in_array
+                    .as_primitive_opt::<$ArrowType>()
+                    .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+
+                let mut values = HashSet::with_capacity(in_array.len());
+                let null_count = in_array.null_count();
+
+                for v in in_array.iter().flatten() {
+                    values.insert(v);
+                }
+
+                Ok(Self { null_count, values })
+            }
+        }
+
+        impl StaticFilter for $Name {
+            fn null_count(&self) -> usize {
+                self.null_count
+            }
+
+            fn contains(&self, v: &dyn Array, negated: bool) -> Result<BooleanArray> {
+                // Handle dictionary arrays by recursing on the values
+                downcast_dictionary_array! {
+                    v => {
+                        let values_contains = self.contains(v.values().as_ref(), negated)?;
+                        let result = take(&values_contains, v.keys(), None)?;
+                        return Ok(downcast_array(result.as_ref()))
+                    }
+                    _ => {}
+                }
+
+                let v = v
+                    .as_primitive_opt::<$ArrowType>()
+                    .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;

Review Comment:
   ```suggestion
                       .ok_or_else(|| exec_datafusion_err!(format!("Failed to downcast an array to a '{}' array", stringify!($ArrowType))))?;
   ```



##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,18 +208,135 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
+// Macro to generate specialized StaticFilter implementations for primitive types
+macro_rules! primitive_static_filter {
+    ($Name:ident, $ArrowType:ty) => {
+        struct $Name {
+            null_count: usize,
+            values: HashSet<<$ArrowType as ArrowPrimitiveType>::Native>,
+        }
+
+        impl $Name {
+            fn try_new(in_array: &ArrayRef) -> Result<Self> {
+                let in_array = in_array
+                    .as_primitive_opt::<$ArrowType>()
+                    .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+
+                let mut values = HashSet::with_capacity(in_array.len());
+                let null_count = in_array.null_count();
+
+                for v in in_array.iter().flatten() {
+                    values.insert(v);
+                }
+
+                Ok(Self { null_count, values })
+            }
+        }
+
+        impl StaticFilter for $Name {
+            fn null_count(&self) -> usize {
+                self.null_count
+            }
+
+            fn contains(&self, v: &dyn Array, negated: bool) -> Result<BooleanArray> {
+                // Handle dictionary arrays by recursing on the values
+                downcast_dictionary_array! {
+                    v => {
+                        let values_contains = self.contains(v.values().as_ref(), negated)?;
+                        let result = take(&values_contains, v.keys(), None)?;
+                        return Ok(downcast_array(result.as_ref()))
+                    }
+                    _ => {}
+                }
+
+                let v = v
+                    .as_primitive_opt::<$ArrowType>()
+                    .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+
+                let haystack_has_nulls = self.null_count > 0;
+
+                let result = match (v.null_count() > 0, haystack_has_nulls, negated) {
+                    (true, _, false) | (false, true, false) => {
+                        // Either needle or haystack has nulls, not negated
+                        BooleanArray::from_iter(v.iter().map(|value| {
+                            match value {
+                                // SQL three-valued logic: null IN (...) is always null
+                                None => None,
+                                Some(v) => {
+                                    if self.values.contains(&v) {
+                                        Some(true)
+                                    } else if haystack_has_nulls {
+                                        // value not in set, but set has nulls -> null
+                                        None
+                                    } else {
+                                        Some(false)
+                                    }
+                                }
+                            }
+                        }))
+                    }
+                    (true, _, true) | (false, true, true) => {
+                        // Either needle or haystack has nulls, negated
+                        BooleanArray::from_iter(v.iter().map(|value| {
+                            match value {
+                                // SQL three-valued logic: null NOT IN (...) is always null
+                                None => None,
+                                Some(v) => {
+                                    if self.values.contains(&v) {
+                                        Some(false)
+                                    } else if haystack_has_nulls {
+                                        // value not in set, but set has nulls -> null
+                                        None
+                                    } else {
+                                        Some(true)
+                                    }
+                                }
+                            }
+                        }))
+                    }
+                    (false, false, false) => {
+                        // no nulls anywhere, not negated
+                        BooleanArray::from_iter(
+                            v.values().iter().map(|value| self.values.contains(value)),
+                        )
+                    }
+                    (false, false, true) => {
+                        // no nulls anywhere, negated
+                        BooleanArray::from_iter(
+                            v.values().iter().map(|value| !self.values.contains(value)),
+                        )
+                    }
+                };
+                Ok(result)
+            }
+        }
+    };
+}
+
+// Generate specialized filters for all integer primitive types
+// Note: Float32 and Float64 are excluded because they don't implement Hash/Eq due to NaN
+primitive_static_filter!(Int8StaticFilter, Int8Type);
+primitive_static_filter!(Int16StaticFilter, Int16Type);
+primitive_static_filter!(Int32StaticFilter, Int32Type);
+primitive_static_filter!(Int64StaticFilter, Int64Type);
+primitive_static_filter!(UInt8StaticFilter, UInt8Type);
+primitive_static_filter!(UInt16StaticFilter, UInt16Type);
+primitive_static_filter!(UInt32StaticFilter, UInt32Type);
+primitive_static_filter!(UInt64StaticFilter, UInt64Type);
+
+// Boolean static filter
+struct BooleanStaticFilter {
     null_count: usize,
-    values: HashSet<i32>,
+    values: HashSet<bool>,
 }
 
-impl Int32StaticFilter {
+impl BooleanStaticFilter {
     fn try_new(in_array: &ArrayRef) -> Result<Self> {
         let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
+            .as_boolean_opt()
             .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;

Review Comment:
   ```suggestion
               .ok_or_else(|| exec_datafusion_err!("Failed to downcast an array to a boolean array"))?;
   ```



##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,18 +208,135 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
+// Macro to generate specialized StaticFilter implementations for primitive types
+macro_rules! primitive_static_filter {
+    ($Name:ident, $ArrowType:ty) => {
+        struct $Name {
+            null_count: usize,
+            values: HashSet<<$ArrowType as ArrowPrimitiveType>::Native>,
+        }
+
+        impl $Name {
+            fn try_new(in_array: &ArrayRef) -> Result<Self> {
+                let in_array = in_array
+                    .as_primitive_opt::<$ArrowType>()
+                    .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;

Review Comment:
   ```suggestion
                       .ok_or_else(|| exec_datafusion_err!(format!("Failed to downcast an array to a '{}' array", stringify!($ArrowType))))?;
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on code in PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#discussion_r2552638215


##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,68 +206,122 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
-    null_count: usize,
-    values: HashSet<i32>,
-}
+// Macro to generate specialized StaticFilter implementations for primitive types
+macro_rules! primitive_static_filter {
+    ($Name:ident, $ArrowType:ty) => {
+        struct $Name {
+            null_count: usize,
+            values: HashSet<<$ArrowType as ArrowPrimitiveType>::Native>,
+        }
 
-impl Int32StaticFilter {
-    fn try_new(in_array: &ArrayRef) -> Result<Self> {
-        let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+        impl $Name {
+            fn try_new(in_array: &ArrayRef) -> Result<Self> {
+                let in_array = in_array
+                    .as_primitive_opt::<$ArrowType>()
+                    .ok_or_else(|| exec_datafusion_err!(format!("Failed to downcast an array to a '{}' array", stringify!($ArrowType))))?;
 
-        let mut values = HashSet::with_capacity(in_array.len());
-        let null_count = in_array.null_count();
+                let mut values = HashSet::with_capacity(in_array.len());
+                let null_count = in_array.null_count();
+
+                for v in in_array.iter().flatten() {
+                    values.insert(v);
+                }
 
-        for v in in_array.iter().flatten() {
-            values.insert(v);
+                Ok(Self { null_count, values })
+            }
         }
 
-        Ok(Self { null_count, values })
-    }
-}
+        impl StaticFilter for $Name {
+            fn null_count(&self) -> usize {
+                self.null_count
+            }
 
-impl StaticFilter for Int32StaticFilter {
-    fn null_count(&self) -> usize {
-        self.null_count
-    }
+            fn contains(&self, v: &dyn Array, negated: bool) -> Result<BooleanArray> {
+                // Handle dictionary arrays by recursing on the values
+                downcast_dictionary_array! {
+                    v => {
+                        let values_contains = self.contains(v.values().as_ref(), negated)?;
+                        let result = take(&values_contains, v.keys(), None)?;
+                        return Ok(downcast_array(result.as_ref()))
+                    }
+                    _ => {}
+                }
 
-    fn contains(&self, v: &dyn Array, negated: bool) -> Result<BooleanArray> {
-        let v = v
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
-
-        let result = match (v.null_count() > 0, negated) {
-            (true, false) => {
-                // has nulls, not negated"
-                BooleanArray::from_iter(
-                    v.iter().map(|value| Some(self.values.contains(&value?))),
-                )
-            }
-            (true, true) => {
-                // has nulls, negated
-                BooleanArray::from_iter(
-                    v.iter().map(|value| Some(!self.values.contains(&value?))),
-                )
-            }
-            (false, false) => {
-                //no null, not negated
-                BooleanArray::from_iter(
-                    v.values().iter().map(|value| self.values.contains(value)),
-                )
-            }
-            (false, true) => {
-                // no null, negated
-                BooleanArray::from_iter(
-                    v.values().iter().map(|value| !self.values.contains(value)),
-                )
+                let v = v
+                    .as_primitive_opt::<$ArrowType>()
+                    .ok_or_else(|| exec_datafusion_err!(format!("Failed to downcast an array to a '{}' array", stringify!($ArrowType))))?;
+
+                let haystack_has_nulls = self.null_count > 0;
+
+                let result = match (v.null_count() > 0, haystack_has_nulls, negated) {
+                    (true, _, false) | (false, true, false) => {
+                        // Either needle or haystack has nulls, not negated
+                        BooleanArray::from_iter(v.iter().map(|value| {
+                            match value {
+                                // SQL three-valued logic: null IN (...) is always null
+                                None => None,
+                                Some(v) => {
+                                    if self.values.contains(&v) {
+                                        Some(true)
+                                    } else if haystack_has_nulls {
+                                        // value not in set, but set has nulls -> null
+                                        None
+                                    } else {
+                                        Some(false)
+                                    }
+                                }
+                            }
+                        }))
+                    }
+                    (true, _, true) | (false, true, true) => {
+                        // Either needle or haystack has nulls, negated
+                        BooleanArray::from_iter(v.iter().map(|value| {
+                            match value {
+                                // SQL three-valued logic: null NOT IN (...) is always null
+                                None => None,
+                                Some(v) => {
+                                    if self.values.contains(&v) {
+                                        Some(false)
+                                    } else if haystack_has_nulls {
+                                        // value not in set, but set has nulls -> null
+                                        None
+                                    } else {
+                                        Some(true)
+                                    }
+                                }
+                            }
+                        }))
+                    }
+                    (false, false, false) => {
+                        // no nulls anywhere, not negated
+                        BooleanArray::from_iter(

Review Comment:
   I do wonder why we don't have faster high-level APIs if this is really important. E.g. `BooleanArray::new_false`, `BooleanArray::new_nulls`, `BooleanArray::new_true` and `BooleanArray::collect_bool(size, iterator)` or something like that.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3625839469

   General comment on the benchmark but... am I reading them wrong, or is the `null_percent` input logic inverted?
   
   ```rust
   fn do_benches(
       c: &mut Criterion,
       array_length: usize,
       in_list_length: usize,
       null_percent: f64,
   ) {
   ...
       let values: Int32Array = (0..array_length)
           .map(|_| rng.random_bool(null_percent).then(|| rng.random()))
           .collect();
   
       let in_list: Vec<_> = (0..in_list_length)
           .map(|_| ScalarValue::Int32(Some(rng.random())))
           .collect();
   
       do_bench(
           c,
           &format!("in_list_i32 ({array_length}, {null_percent}) IN ({in_list_length}, 0)"),
           Arc::new(values),
           &in_list,
       )
   ```
   
   When `null_percent` is `0`, won't this just create a `array_length` long `values` array of `NULL`s?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on code in PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#discussion_r2599863807


##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,68 +211,127 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
-    null_count: usize,
-    values: HashSet<i32>,
-}
+// Macro to generate specialized StaticFilter implementations for primitive types
+macro_rules! primitive_static_filter {
+    ($Name:ident, $ArrowType:ty) => {
+        struct $Name {
+            null_count: usize,
+            values: HashSet<<$ArrowType as ArrowPrimitiveType>::Native>,
+        }
 
-impl Int32StaticFilter {
-    fn try_new(in_array: &ArrayRef) -> Result<Self> {
-        let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+        impl $Name {
+            fn try_new(in_array: &ArrayRef) -> Result<Self> {
+                let in_array = in_array
+                    .as_primitive_opt::<$ArrowType>()
+                    .ok_or_else(|| exec_datafusion_err!("Failed to downcast an array to a '{}' array", stringify!($ArrowType)))?;
 
-        let mut values = HashSet::with_capacity(in_array.len());
-        let null_count = in_array.null_count();
+                let mut values = HashSet::with_capacity(in_array.len());
+                let null_count = in_array.null_count();
+
+                for v in in_array.iter().flatten() {
+                    values.insert(v);
+                }
 
-        for v in in_array.iter().flatten() {
-            values.insert(v);
+                Ok(Self { null_count, values })
+            }
         }
 
-        Ok(Self { null_count, values })
-    }
-}
+        impl StaticFilter for $Name {
+            fn null_count(&self) -> usize {
+                self.null_count
+            }
 
-impl StaticFilter for Int32StaticFilter {
-    fn null_count(&self) -> usize {
-        self.null_count
-    }
+            fn contains(&self, v: &dyn Array, negated: bool) -> Result<BooleanArray> {
+                // Handle dictionary arrays by recursing on the values
+                downcast_dictionary_array! {
+                    v => {
+                        let values_contains = self.contains(v.values().as_ref(), negated)?;
+                        let result = take(&values_contains, v.keys(), None)?;
+                        return Ok(downcast_array(result.as_ref()))
+                    }
+                    _ => {}
+                }
 
-    fn contains(&self, v: &dyn Array, negated: bool) -> Result<BooleanArray> {
-        let v = v
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
-
-        let result = match (v.null_count() > 0, negated) {
-            (true, false) => {
-                // has nulls, not negated"
-                BooleanArray::from_iter(
-                    v.iter().map(|value| Some(self.values.contains(&value?))),
-                )
-            }
-            (true, true) => {
-                // has nulls, negated
-                BooleanArray::from_iter(
-                    v.iter().map(|value| Some(!self.values.contains(&value?))),
-                )
-            }
-            (false, false) => {
-                //no null, not negated
-                BooleanArray::from_iter(
-                    v.values().iter().map(|value| self.values.contains(value)),
-                )
-            }
-            (false, true) => {
-                // no null, negated
-                BooleanArray::from_iter(
-                    v.values().iter().map(|value| !self.values.contains(value)),
-                )
+                let v = v
+                    .as_primitive_opt::<$ArrowType>()
+                    .ok_or_else(|| exec_datafusion_err!("Failed to downcast an array to a '{}' array", stringify!($ArrowType)))?;
+
+                let haystack_has_nulls = self.null_count > 0;
+
+                let result = match (v.null_count() > 0, haystack_has_nulls, negated) {
+                    (true, _, false) | (false, true, false) => {

Review Comment:
   Thanks applied in #19050



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "alamb-ghbot (via GitHub)" <gi...@apache.org>.
alamb-ghbot commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3638031098

   🤖 `./gh_compare_branch_bench.sh` [compare_branch_bench.sh](https://github.com/alamb/datafusion-benchmarking/blob/main/scripts/compare_branch_bench.sh) Running
   Linux aal-dev 6.14.0-1018-gcp #19~24.04.1-Ubuntu SMP Wed Sep 24 23:23:09 UTC 2025 x86_64 x86_64 x86_64 GNU/Linux
   Comparing specialize (c1a29a251c7c7710cb45650e409160437ecc3e7f) to e8a0829b7a2044ab477784d60ed2d208b97f5042 [diff](https://github.com/apache/datafusion/compare/e8a0829b7a2044ab477784d60ed2d208b97f5042..c1a29a251c7c7710cb45650e409160437ecc3e7f)
   BENCH_NAME=in_list
   BENCH_COMMAND=cargo bench --all-features --bench in_list
   BENCH_FILTER=
   BENCH_BRANCH_NAME=specialize
   Results will be posted here when complete
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "alamb-ghbot (via GitHub)" <gi...@apache.org>.
alamb-ghbot commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3638639573

   🤖 `./gh_compare_branch_bench.sh` [compare_branch_bench.sh](https://github.com/alamb/datafusion-benchmarking/blob/main/scripts/compare_branch_bench.sh) Running
   Linux aal-dev 6.14.0-1018-gcp #19~24.04.1-Ubuntu SMP Wed Sep 24 23:23:09 UTC 2025 x86_64 x86_64 x86_64 GNU/Linux
   Comparing specialize (2f2c60da1b59f314ebb18690f0003220c0ec10b9) to e8a0829b7a2044ab477784d60ed2d208b97f5042 [diff](https://github.com/apache/datafusion/compare/e8a0829b7a2044ab477784d60ed2d208b97f5042..2f2c60da1b59f314ebb18690f0003220c0ec10b9)
   BENCH_NAME=in_list
   BENCH_COMMAND=cargo bench --all-features --bench in_list
   BENCH_FILTER=
   BENCH_BRANCH_NAME=specialize
   Results will be posted here when complete
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#discussion_r2612206421


##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -138,9 +142,20 @@ fn instantiate_static_filter(
     in_array: ArrayRef,
 ) -> Result<Arc<dyn StaticFilter + Send + Sync>> {
     match in_array.data_type() {
+        // Integer primitive types
+        DataType::Int8 => Ok(Arc::new(Int8StaticFilter::try_new(&in_array)?)),
+        DataType::Int16 => Ok(Arc::new(Int16StaticFilter::try_new(&in_array)?)),
         DataType::Int32 => Ok(Arc::new(Int32StaticFilter::try_new(&in_array)?)),
+        DataType::Int64 => Ok(Arc::new(Int64StaticFilter::try_new(&in_array)?)),
+        DataType::UInt8 => Ok(Arc::new(UInt8StaticFilter::try_new(&in_array)?)),
+        DataType::UInt16 => Ok(Arc::new(UInt16StaticFilter::try_new(&in_array)?)),
+        DataType::UInt32 => Ok(Arc::new(UInt32StaticFilter::try_new(&in_array)?)),
+        DataType::UInt64 => Ok(Arc::new(UInt64StaticFilter::try_new(&in_array)?)),
+        // Float primitive types (use ordered wrappers for Hash/Eq)
+        DataType::Float32 => Ok(Arc::new(Float32StaticFilter::try_new(&in_array)?)),
+        DataType::Float64 => Ok(Arc::new(Float64StaticFilter::try_new(&in_array)?)),

Review Comment:
   Do we know if adding an optimized version of the binary / string type comparisons is tracked with a ticket?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3601686487

   I am hoping to look at this PR today or tomorrow and help push it along


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3603356096

   I realized this new implementation differs from the existing one in ways which fix some bugs. I opened https://github.com/apache/datafusion/pull/19050 to demonstrate those bugs. So maybe lets first fix the bugs and merge the new tests, then we can continue here?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#discussion_r2602527959


##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,65 +248,414 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
-    null_count: usize,
-    values: HashSet<i32>,
+/// Threshold for switching from sorted Vec (binary search) to HashSet
+/// For small lists, binary search has better cache locality and lower overhead
+/// Maximum list size for using sorted lookup (binary search).
+/// Lists with more elements use hash lookup instead.
+const SORTED_LOOKUP_MAX_LEN: usize = 8;
+
+/// Helper to build a BooleanArray result for IN list operations.
+/// Handles SQL three-valued logic for NULL values.
+///
+/// # Arguments
+/// * `len` - Number of elements in the needle array
+/// * `needle_nulls` - Optional validity buffer from the needle array
+/// * `haystack_has_nulls` - Whether the IN list contains NULL values
+/// * `negated` - Whether this is a NOT IN operation
+/// * `contains` - Closure that returns whether needle[i] is found in the haystack
+#[inline]
+fn build_in_list_result<C>(
+    len: usize,
+    needle_nulls: Option<&NullBuffer>,
+    haystack_has_nulls: bool,
+    negated: bool,
+    contains: C,
+) -> BooleanArray
+where
+    C: Fn(usize) -> bool,
+{
+    // Use collect_bool for all paths - it's vectorized and faster than element-by-element append.
+    // Match on (needle_has_nulls, haystack_has_nulls, negated) to specialize each case.
+    match (needle_nulls, haystack_has_nulls, negated) {
+        // Haystack has nulls: result is NULL when not found (might match the NULL)
+        // values_buf == nulls_buf, so compute once and clone
+        (Some(validity), true, false) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let buf = validity.inner() & &contains_buf;
+            BooleanArray::new(buf.clone(), Some(NullBuffer::new(buf)))
+        }
+        (None, true, false) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            BooleanArray::new(buf.clone(), Some(NullBuffer::new(buf)))
+        }
+        (Some(validity), true, true) => {
+            // Compute nulls_buf via SIMD AND, then derive values_buf via XOR.
+            // Uses identity: A & !B = A ^ (A & B) to get values from nulls.
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let nulls_buf = validity.inner() & &contains_buf;
+            let values_buf = validity.inner() ^ &nulls_buf; // valid & !contains
+            BooleanArray::new(values_buf, Some(NullBuffer::new(nulls_buf)))
+        }
+        (None, true, true) => {
+            // No needle nulls, but haystack has nulls
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = !&contains_buf;
+            BooleanArray::new(values_buf, Some(NullBuffer::new(contains_buf)))
+        }
+        // Only needle has nulls: nulls_buf is just validity (reuse it directly!)
+        (Some(validity), false, false) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = validity.inner() & &contains_buf;
+            BooleanArray::new(values_buf, Some(validity.clone()))
+        }
+        (Some(validity), false, true) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = validity.inner() & &(!&contains_buf);
+            BooleanArray::new(values_buf, Some(validity.clone()))
+        }
+        // No nulls anywhere: no validity buffer needed
+        (None, false, false) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            BooleanArray::new(buf, None)
+        }
+        (None, false, true) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| !contains(i));
+            BooleanArray::new(buf, None)
+        }
+    }
 }
 
-impl Int32StaticFilter {
-    fn try_new(in_array: &ArrayRef) -> Result<Self> {
-        let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+/// Sorted lookup using binary search. Best for small lists (< 8 elements).
+struct SortedLookup<T>(Vec<T>);
 
-        let mut values = HashSet::with_capacity(in_array.len());
-        let null_count = in_array.null_count();
+impl<T: Ord> SortedLookup<T> {
+    fn new(mut values: Vec<T>) -> Self {
+        values.sort_unstable();
+        values.dedup();
+        Self(values)
+    }
 
-        for v in in_array.iter().flatten() {
-            values.insert(v);
-        }
+    #[inline]
+    fn contains(&self, value: &T) -> bool {
+        self.0.binary_search(value).is_ok()

Review Comment:
   Yes that's what I'm seeing :) I have some really nice perf improvements with some dedicated linear search. I'll clean up my hacky vibe coded poc and submit another PR to the branch.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on code in PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#discussion_r2603578892


##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,65 +248,414 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
-    null_count: usize,
-    values: HashSet<i32>,
+/// Threshold for switching from sorted Vec (binary search) to HashSet
+/// For small lists, binary search has better cache locality and lower overhead
+/// Maximum list size for using sorted lookup (binary search).
+/// Lists with more elements use hash lookup instead.
+const SORTED_LOOKUP_MAX_LEN: usize = 8;
+
+/// Helper to build a BooleanArray result for IN list operations.
+/// Handles SQL three-valued logic for NULL values.
+///
+/// # Arguments
+/// * `len` - Number of elements in the needle array
+/// * `needle_nulls` - Optional validity buffer from the needle array
+/// * `haystack_has_nulls` - Whether the IN list contains NULL values
+/// * `negated` - Whether this is a NOT IN operation
+/// * `contains` - Closure that returns whether needle[i] is found in the haystack
+#[inline]
+fn build_in_list_result<C>(
+    len: usize,
+    needle_nulls: Option<&NullBuffer>,
+    haystack_has_nulls: bool,
+    negated: bool,
+    contains: C,
+) -> BooleanArray
+where
+    C: Fn(usize) -> bool,
+{
+    // Use collect_bool for all paths - it's vectorized and faster than element-by-element append.
+    // Match on (needle_has_nulls, haystack_has_nulls, negated) to specialize each case.
+    match (needle_nulls, haystack_has_nulls, negated) {
+        // Haystack has nulls: result is NULL when not found (might match the NULL)
+        // values_buf == nulls_buf, so compute once and clone
+        (Some(validity), true, false) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let buf = validity.inner() & &contains_buf;
+            BooleanArray::new(buf.clone(), Some(NullBuffer::new(buf)))
+        }
+        (None, true, false) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            BooleanArray::new(buf.clone(), Some(NullBuffer::new(buf)))
+        }
+        (Some(validity), true, true) => {
+            // Compute nulls_buf via SIMD AND, then derive values_buf via XOR.
+            // Uses identity: A & !B = A ^ (A & B) to get values from nulls.
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let nulls_buf = validity.inner() & &contains_buf;
+            let values_buf = validity.inner() ^ &nulls_buf; // valid & !contains
+            BooleanArray::new(values_buf, Some(NullBuffer::new(nulls_buf)))
+        }
+        (None, true, true) => {
+            // No needle nulls, but haystack has nulls
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = !&contains_buf;
+            BooleanArray::new(values_buf, Some(NullBuffer::new(contains_buf)))
+        }
+        // Only needle has nulls: nulls_buf is just validity (reuse it directly!)
+        (Some(validity), false, false) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = validity.inner() & &contains_buf;
+            BooleanArray::new(values_buf, Some(validity.clone()))
+        }
+        (Some(validity), false, true) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = validity.inner() & &(!&contains_buf);
+            BooleanArray::new(values_buf, Some(validity.clone()))
+        }
+        // No nulls anywhere: no validity buffer needed
+        (None, false, false) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            BooleanArray::new(buf, None)
+        }
+        (None, false, true) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| !contains(i));
+            BooleanArray::new(buf, None)
+        }
+    }
 }
 
-impl Int32StaticFilter {
-    fn try_new(in_array: &ArrayRef) -> Result<Self> {
-        let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+/// Sorted lookup using binary search. Best for small lists (< 8 elements).
+struct SortedLookup<T>(Vec<T>);
 
-        let mut values = HashSet::with_capacity(in_array.len());
-        let null_count = in_array.null_count();
+impl<T: Ord> SortedLookup<T> {
+    fn new(mut values: Vec<T>) -> Self {
+        values.sort_unstable();
+        values.dedup();
+        Self(values)
+    }
 
-        for v in in_array.iter().flatten() {
-            values.insert(v);
-        }
+    #[inline]
+    fn contains(&self, value: &T) -> bool {
+        self.0.binary_search(value).is_ok()

Review Comment:
   Do you think it's okay if we re-focus this on just adding specialized hash implementations for the missing primitive types?



##########
datafusion/physical-expr/src/expressions/in_list.rs:
##########
@@ -198,65 +248,414 @@ impl ArrayStaticFilter {
     }
 }
 
-struct Int32StaticFilter {
-    null_count: usize,
-    values: HashSet<i32>,
+/// Threshold for switching from sorted Vec (binary search) to HashSet
+/// For small lists, binary search has better cache locality and lower overhead
+/// Maximum list size for using sorted lookup (binary search).
+/// Lists with more elements use hash lookup instead.
+const SORTED_LOOKUP_MAX_LEN: usize = 8;
+
+/// Helper to build a BooleanArray result for IN list operations.
+/// Handles SQL three-valued logic for NULL values.
+///
+/// # Arguments
+/// * `len` - Number of elements in the needle array
+/// * `needle_nulls` - Optional validity buffer from the needle array
+/// * `haystack_has_nulls` - Whether the IN list contains NULL values
+/// * `negated` - Whether this is a NOT IN operation
+/// * `contains` - Closure that returns whether needle[i] is found in the haystack
+#[inline]
+fn build_in_list_result<C>(
+    len: usize,
+    needle_nulls: Option<&NullBuffer>,
+    haystack_has_nulls: bool,
+    negated: bool,
+    contains: C,
+) -> BooleanArray
+where
+    C: Fn(usize) -> bool,
+{
+    // Use collect_bool for all paths - it's vectorized and faster than element-by-element append.
+    // Match on (needle_has_nulls, haystack_has_nulls, negated) to specialize each case.
+    match (needle_nulls, haystack_has_nulls, negated) {
+        // Haystack has nulls: result is NULL when not found (might match the NULL)
+        // values_buf == nulls_buf, so compute once and clone
+        (Some(validity), true, false) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let buf = validity.inner() & &contains_buf;
+            BooleanArray::new(buf.clone(), Some(NullBuffer::new(buf)))
+        }
+        (None, true, false) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            BooleanArray::new(buf.clone(), Some(NullBuffer::new(buf)))
+        }
+        (Some(validity), true, true) => {
+            // Compute nulls_buf via SIMD AND, then derive values_buf via XOR.
+            // Uses identity: A & !B = A ^ (A & B) to get values from nulls.
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let nulls_buf = validity.inner() & &contains_buf;
+            let values_buf = validity.inner() ^ &nulls_buf; // valid & !contains
+            BooleanArray::new(values_buf, Some(NullBuffer::new(nulls_buf)))
+        }
+        (None, true, true) => {
+            // No needle nulls, but haystack has nulls
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = !&contains_buf;
+            BooleanArray::new(values_buf, Some(NullBuffer::new(contains_buf)))
+        }
+        // Only needle has nulls: nulls_buf is just validity (reuse it directly!)
+        (Some(validity), false, false) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = validity.inner() & &contains_buf;
+            BooleanArray::new(values_buf, Some(validity.clone()))
+        }
+        (Some(validity), false, true) => {
+            let contains_buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            let values_buf = validity.inner() & &(!&contains_buf);
+            BooleanArray::new(values_buf, Some(validity.clone()))
+        }
+        // No nulls anywhere: no validity buffer needed
+        (None, false, false) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| contains(i));
+            BooleanArray::new(buf, None)
+        }
+        (None, false, true) => {
+            let buf = BooleanBuffer::collect_bool(len, |i| !contains(i));
+            BooleanArray::new(buf, None)
+        }
+    }
 }
 
-impl Int32StaticFilter {
-    fn try_new(in_array: &ArrayRef) -> Result<Self> {
-        let in_array = in_array
-            .as_primitive_opt::<Int32Type>()
-            .ok_or_else(|| exec_datafusion_err!("Failed to downcast array"))?;
+/// Sorted lookup using binary search. Best for small lists (< 8 elements).
+struct SortedLookup<T>(Vec<T>);
 
-        let mut values = HashSet::with_capacity(in_array.len());
-        let null_count = in_array.null_count();
+impl<T: Ord> SortedLookup<T> {
+    fn new(mut values: Vec<T>) -> Self {
+        values.sort_unstable();
+        values.dedup();
+        Self(values)
+    }
 
-        for v in in_array.iter().flatten() {
-            values.insert(v);
-        }
+    #[inline]
+    fn contains(&self, value: &T) -> bool {
+        self.0.binary_search(value).is_ok()

Review Comment:
   Do you think it's okay if we re-focus this PR on just adding specialized hash implementations for the missing primitive types?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3634442805

   run benchmarks in_list


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "alamb-ghbot (via GitHub)" <gi...@apache.org>.
alamb-ghbot commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3634537391

   🤖 Hi @alamb, thanks for the request (https://github.com/apache/datafusion/pull/18832#issuecomment-3634537320).
   
   [`scrape_comments.py`](https://github.com/alamb/datafusion-benchmarking/blob/main/scripts/scrape_comments.py) only supports whitelisted benchmarks.
   - Standard: clickbench_1, clickbench_extended, clickbench_partitioned, clickbench_pushdown, tpch, tpch10, tpch_mem, tpch_mem10
   - Criterion: aggregate_query_sql, aggregate_vectorized, case_when, in_list, sql_planner
   
   Please choose one or more of these with `run benchmark <name>` or `run benchmark <name1> <name2>...`


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] add specialized InList implementations for common scalar types [datafusion]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on PR #18832:
URL: https://github.com/apache/datafusion/pull/18832#issuecomment-3634542497

   The key is `benchmark` vs `benchmarks` fyi. I can make a PR to accept both tomorrow.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org