Skip to content

Commit dc99a52

Browse files
perf: skip validation of dictionary keys if all null (#9322)
# Which issue does this PR close? <!-- We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. --> - Closes #9321 . # Rationale for this change <!-- Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed. Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes. --> Improve the performance of creating a dictionary array that is all nulls. # What changes are included in this PR? <!-- There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR. --> The `try_new` constructor skips the key validation if all the keys are null. Adds a benchmark for creating the all null dictionary to verify the performance improvement. | Benchmark | Before | After | Change | |-----------|--------|-------|---------| | null_dict/len=128 | 133.37 ns | 98.222 ns | -25.659% | | null_dict/len=1536 | 623.39 ns | 286.11 ns | -57.361% | | null_dict/len=8092 | 3.0252 µs | 1.0719 µs | -66.573% | # Are these changes tested? <!-- We typically require tests for all PRs in order to: 1. Prevent the code from being accidentally broken by subsequent changes 2. Serve as another way to document the expected behavior of the code If tests are not included in your PR, please explain why (for example, are they covered by existing tests)? --> I added a smoke test that calls the constructor with an all nulls key column and asserts the result is OK. I wasn't sure about the best way to test this (open to suggestions). # Are there any user-facing changes? <!-- If there are user-facing changes then we may require documentation to be updated before approving the PR. If there are any breaking changes to public APIs, please call them out. --> no
1 parent c1033d1 commit dc99a52

File tree

3 files changed

+68
-11
lines changed

3 files changed

+68
-11
lines changed

arrow-array/Cargo.toml

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,10 @@ harness = false
7575
name = "fixed_size_list_array"
7676
harness = false
7777

78+
[[bench]]
79+
name = "null_dict"
80+
harness = false
81+
7882
[[bench]]
7983
name = "decimal_overflow"
8084
harness = false
@@ -85,4 +89,4 @@ harness = false
8589

8690
[[bench]]
8791
name = "record_batch"
88-
harness = false
92+
harness = false

arrow-array/benches/null_dict.rs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// Licensed to the Apache Software Foundation (ASF) under one
2+
// or more contributor license agreements. See the NOTICE file
3+
// distributed with this work for additional information
4+
// regarding copyright ownership. The ASF licenses this file
5+
// to you under the Apache License, Version 2.0 (the
6+
// "License"); you may not use this file except in compliance
7+
// with the License. You may obtain a copy of the License at
8+
//
9+
// http://www.apache.org/licenses/LICENSE-2.0
10+
//
11+
// Unless required by applicable law or agreed to in writing,
12+
// software distributed under the License is distributed on an
13+
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
// KIND, either express or implied. See the License for the
15+
// specific language governing permissions and limitations
16+
// under the License.
17+
use arrow_array::{DictionaryArray, StringArray, UInt16Array};
18+
use std::sync::Arc;
19+
20+
use criterion::*;
21+
22+
fn criterion_benchmark(c: &mut Criterion) {
23+
let dict_vals = Arc::new(StringArray::from_iter_values(["a", "b", "c"]));
24+
for len in [128, 1536, 8092] {
25+
c.bench_function(&format!("null_dict/len={len}"), |b| {
26+
b.iter_batched(
27+
|| dict_vals.clone(),
28+
|dict_vals| {
29+
std::hint::black_box(DictionaryArray::new(
30+
UInt16Array::new_null(len),
31+
dict_vals.clone(),
32+
))
33+
},
34+
BatchSize::SmallInput,
35+
);
36+
});
37+
}
38+
}
39+
40+
criterion_group!(benches, criterion_benchmark);
41+
criterion_main!(benches);

arrow-array/src/array/dictionary_array.rs

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -292,17 +292,20 @@ impl<K: ArrowDictionaryKeyType> DictionaryArray<K> {
292292
Box::new(values.data_type().clone()),
293293
);
294294

295-
let zero = K::Native::usize_as(0);
296-
let values_len = values.len();
295+
// // we can skip the validating the keys if they are all null
296+
let all_null = keys.null_count() == keys.len();
297297

298-
if let Some((idx, v)) =
299-
keys.values().iter().enumerate().find(|(idx, v)| {
298+
if !all_null {
299+
let zero = K::Native::usize_as(0);
300+
let values_len = values.len();
301+
302+
if let Some((idx, v)) = keys.values().iter().enumerate().find(|(idx, v)| {
300303
(v.is_lt(zero) || v.as_usize() >= values_len) && keys.is_valid(*idx)
301-
})
302-
{
303-
return Err(ArrowError::InvalidArgumentError(format!(
304-
"Invalid dictionary key {v:?} at index {idx}, expected 0 <= key < {values_len}",
305-
)));
304+
}) {
305+
return Err(ArrowError::InvalidArgumentError(format!(
306+
"Invalid dictionary key {v:?} at index {idx}, expected 0 <= key < {values_len}",
307+
)));
308+
}
306309
}
307310

308311
Ok(Self {
@@ -1047,7 +1050,7 @@ impl<K: ArrowDictionaryKeyType> AnyDictionaryArray for DictionaryArray<K> {
10471050
mod tests {
10481051
use super::*;
10491052
use crate::cast::as_dictionary_array;
1050-
use crate::{Int8Array, Int16Array, Int32Array, RunArray};
1053+
use crate::{Int8Array, Int16Array, Int32Array, RunArray, UInt8Array};
10511054
use arrow_buffer::{Buffer, ToByteSlice};
10521055

10531056
#[test]
@@ -1528,4 +1531,13 @@ mod tests {
15281531
let dictionary = DictionaryArray::new(keys, Arc::new(Int32Array::new_null(2)));
15291532
assert_eq!(&dictionary.normalized_keys(), &[1, 0, 1])
15301533
}
1534+
1535+
#[test]
1536+
fn test_all_null_dict() {
1537+
let all_null_dict_arr = DictionaryArray::try_new(
1538+
UInt8Array::new_null(10),
1539+
Arc::new(StringArray::from_iter_values(["a"])),
1540+
);
1541+
assert!(all_null_dict_arr.is_ok())
1542+
}
15311543
}

0 commit comments

Comments
 (0)