Skip to content

Commit bb4e0ec

Browse files
authored
perf: Optimize starts_with and ends_with for scalar arguments (#19516)
## 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. For example `Closes #123` indicates that this PR will close issue #123. --> - Closes #. ## 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. --> - Scalar argument optimization delivers 3.6x-8x speedup for the common case of starts_with(column, 'literal') or ends_with(column, 'literal') - StringViewArray benefits even more (~6-8x) than StringArray (~3.6-3.8x) - The optimization uses Arrow's Scalar wrapper to avoid broadcasting scalar values to full arrays ### starts_with | Benchmark | Before | After | Speedup | |--------------------------|----------|----------|---------| | StringArray + scalar | 32.38 µs | 8.49 µs | 3.8x | | StringViewArray + scalar | 78.15 µs | 9.82 µs | 8.0x | ### ends_with | Benchmark | Before | After | Speedup | |--------------------------|----------|----------|---------| | StringArray + scalar | 32.76 µs | 9.06 µs | 3.6x | | StringViewArray + scalar | 76.44 µs | 12.04 µs | 6.4x | ## 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. --> Handle all combinations of array and scalar arguments without converting scalars to arrays ## 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)? --> Yes, new unit tests added in this PR. ## 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 add the `api change` label. --> No, just faster performance.
1 parent d825e5f commit bb4e0ec

File tree

5 files changed

+868
-79
lines changed

5 files changed

+868
-79
lines changed

datafusion/functions/Cargo.toml

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,3 +254,13 @@ required-features = ["unicode_expressions"]
254254
harness = false
255255
name = "find_in_set"
256256
required-features = ["unicode_expressions"]
257+
258+
[[bench]]
259+
harness = false
260+
name = "starts_with"
261+
required-features = ["string_expressions"]
262+
263+
[[bench]]
264+
harness = false
265+
name = "ends_with"
266+
required-features = ["string_expressions"]
Lines changed: 185 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,185 @@
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+
18+
extern crate criterion;
19+
20+
use arrow::array::{StringArray, StringViewArray};
21+
use arrow::datatypes::{DataType, Field};
22+
use criterion::{Criterion, criterion_group, criterion_main};
23+
use datafusion_common::ScalarValue;
24+
use datafusion_common::config::ConfigOptions;
25+
use datafusion_expr::{ColumnarValue, ScalarFunctionArgs};
26+
use rand::distr::Alphanumeric;
27+
use rand::prelude::StdRng;
28+
use rand::{Rng, SeedableRng};
29+
use std::hint::black_box;
30+
use std::sync::Arc;
31+
32+
/// Generate a StringArray/StringViewArray with random ASCII strings
33+
fn gen_string_array(
34+
n_rows: usize,
35+
str_len: usize,
36+
is_string_view: bool,
37+
) -> ColumnarValue {
38+
let mut rng = StdRng::seed_from_u64(42);
39+
let strings: Vec<Option<String>> = (0..n_rows)
40+
.map(|_| {
41+
let s: String = (&mut rng)
42+
.sample_iter(&Alphanumeric)
43+
.take(str_len)
44+
.map(char::from)
45+
.collect();
46+
Some(s)
47+
})
48+
.collect();
49+
50+
if is_string_view {
51+
ColumnarValue::Array(Arc::new(StringViewArray::from(strings)))
52+
} else {
53+
ColumnarValue::Array(Arc::new(StringArray::from(strings)))
54+
}
55+
}
56+
57+
/// Generate a scalar suffix string
58+
fn gen_scalar_suffix(suffix_str: &str, is_string_view: bool) -> ColumnarValue {
59+
if is_string_view {
60+
ColumnarValue::Scalar(ScalarValue::Utf8View(Some(suffix_str.to_string())))
61+
} else {
62+
ColumnarValue::Scalar(ScalarValue::Utf8(Some(suffix_str.to_string())))
63+
}
64+
}
65+
66+
/// Generate an array of suffix strings (same string repeated)
67+
fn gen_array_suffix(
68+
suffix_str: &str,
69+
n_rows: usize,
70+
is_string_view: bool,
71+
) -> ColumnarValue {
72+
let strings: Vec<Option<String>> =
73+
(0..n_rows).map(|_| Some(suffix_str.to_string())).collect();
74+
75+
if is_string_view {
76+
ColumnarValue::Array(Arc::new(StringViewArray::from(strings)))
77+
} else {
78+
ColumnarValue::Array(Arc::new(StringArray::from(strings)))
79+
}
80+
}
81+
82+
fn criterion_benchmark(c: &mut Criterion) {
83+
let ends_with = datafusion_functions::string::ends_with();
84+
let n_rows = 8192;
85+
let str_len = 128;
86+
let suffix_str = "xyz"; // A pattern that likely won't match
87+
88+
// Benchmark: StringArray with scalar suffix (the optimized path)
89+
let str_array = gen_string_array(n_rows, str_len, false);
90+
let scalar_suffix = gen_scalar_suffix(suffix_str, false);
91+
let arg_fields = vec![
92+
Field::new("a", DataType::Utf8, true).into(),
93+
Field::new("b", DataType::Utf8, true).into(),
94+
];
95+
let return_field = Field::new("f", DataType::Boolean, true).into();
96+
let config_options = Arc::new(ConfigOptions::default());
97+
98+
c.bench_function("ends_with_StringArray_scalar_suffix", |b| {
99+
b.iter(|| {
100+
black_box(ends_with.invoke_with_args(ScalarFunctionArgs {
101+
args: vec![str_array.clone(), scalar_suffix.clone()],
102+
arg_fields: arg_fields.clone(),
103+
number_rows: n_rows,
104+
return_field: Arc::clone(&return_field),
105+
config_options: Arc::clone(&config_options),
106+
}))
107+
})
108+
});
109+
110+
// Benchmark: StringArray with array suffix (for comparison)
111+
let array_suffix = gen_array_suffix(suffix_str, n_rows, false);
112+
c.bench_function("ends_with_StringArray_array_suffix", |b| {
113+
b.iter(|| {
114+
black_box(ends_with.invoke_with_args(ScalarFunctionArgs {
115+
args: vec![str_array.clone(), array_suffix.clone()],
116+
arg_fields: arg_fields.clone(),
117+
number_rows: n_rows,
118+
return_field: Arc::clone(&return_field),
119+
config_options: Arc::clone(&config_options),
120+
}))
121+
})
122+
});
123+
124+
// Benchmark: StringViewArray with scalar suffix (the optimized path)
125+
let str_view_array = gen_string_array(n_rows, str_len, true);
126+
let scalar_suffix_view = gen_scalar_suffix(suffix_str, true);
127+
let arg_fields_view = vec![
128+
Field::new("a", DataType::Utf8View, true).into(),
129+
Field::new("b", DataType::Utf8View, true).into(),
130+
];
131+
132+
c.bench_function("ends_with_StringViewArray_scalar_suffix", |b| {
133+
b.iter(|| {
134+
black_box(ends_with.invoke_with_args(ScalarFunctionArgs {
135+
args: vec![str_view_array.clone(), scalar_suffix_view.clone()],
136+
arg_fields: arg_fields_view.clone(),
137+
number_rows: n_rows,
138+
return_field: Arc::clone(&return_field),
139+
config_options: Arc::clone(&config_options),
140+
}))
141+
})
142+
});
143+
144+
// Benchmark: StringViewArray with array suffix (for comparison)
145+
let array_suffix_view = gen_array_suffix(suffix_str, n_rows, true);
146+
c.bench_function("ends_with_StringViewArray_array_suffix", |b| {
147+
b.iter(|| {
148+
black_box(ends_with.invoke_with_args(ScalarFunctionArgs {
149+
args: vec![str_view_array.clone(), array_suffix_view.clone()],
150+
arg_fields: arg_fields_view.clone(),
151+
number_rows: n_rows,
152+
return_field: Arc::clone(&return_field),
153+
config_options: Arc::clone(&config_options),
154+
}))
155+
})
156+
});
157+
158+
// Benchmark different string lengths with scalar suffix
159+
for str_len in [8, 32, 128, 512] {
160+
let str_array = gen_string_array(n_rows, str_len, true);
161+
let scalar_suffix = gen_scalar_suffix(suffix_str, true);
162+
let arg_fields = vec![
163+
Field::new("a", DataType::Utf8View, true).into(),
164+
Field::new("b", DataType::Utf8View, true).into(),
165+
];
166+
167+
c.bench_function(
168+
&format!("ends_with_StringViewArray_scalar_strlen_{str_len}"),
169+
|b| {
170+
b.iter(|| {
171+
black_box(ends_with.invoke_with_args(ScalarFunctionArgs {
172+
args: vec![str_array.clone(), scalar_suffix.clone()],
173+
arg_fields: arg_fields.clone(),
174+
number_rows: n_rows,
175+
return_field: Arc::clone(&return_field),
176+
config_options: Arc::clone(&config_options),
177+
}))
178+
})
179+
},
180+
);
181+
}
182+
}
183+
184+
criterion_group!(benches, criterion_benchmark);
185+
criterion_main!(benches);
Lines changed: 185 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,185 @@
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+
18+
extern crate criterion;
19+
20+
use arrow::array::{StringArray, StringViewArray};
21+
use arrow::datatypes::{DataType, Field};
22+
use criterion::{Criterion, criterion_group, criterion_main};
23+
use datafusion_common::ScalarValue;
24+
use datafusion_common::config::ConfigOptions;
25+
use datafusion_expr::{ColumnarValue, ScalarFunctionArgs};
26+
use rand::distr::Alphanumeric;
27+
use rand::prelude::StdRng;
28+
use rand::{Rng, SeedableRng};
29+
use std::hint::black_box;
30+
use std::sync::Arc;
31+
32+
/// Generate a StringArray/StringViewArray with random ASCII strings
33+
fn gen_string_array(
34+
n_rows: usize,
35+
str_len: usize,
36+
is_string_view: bool,
37+
) -> ColumnarValue {
38+
let mut rng = StdRng::seed_from_u64(42);
39+
let strings: Vec<Option<String>> = (0..n_rows)
40+
.map(|_| {
41+
let s: String = (&mut rng)
42+
.sample_iter(&Alphanumeric)
43+
.take(str_len)
44+
.map(char::from)
45+
.collect();
46+
Some(s)
47+
})
48+
.collect();
49+
50+
if is_string_view {
51+
ColumnarValue::Array(Arc::new(StringViewArray::from(strings)))
52+
} else {
53+
ColumnarValue::Array(Arc::new(StringArray::from(strings)))
54+
}
55+
}
56+
57+
/// Generate a scalar prefix string
58+
fn gen_scalar_prefix(prefix_str: &str, is_string_view: bool) -> ColumnarValue {
59+
if is_string_view {
60+
ColumnarValue::Scalar(ScalarValue::Utf8View(Some(prefix_str.to_string())))
61+
} else {
62+
ColumnarValue::Scalar(ScalarValue::Utf8(Some(prefix_str.to_string())))
63+
}
64+
}
65+
66+
/// Generate an array of prefix strings (same string repeated)
67+
fn gen_array_prefix(
68+
prefix_str: &str,
69+
n_rows: usize,
70+
is_string_view: bool,
71+
) -> ColumnarValue {
72+
let strings: Vec<Option<String>> =
73+
(0..n_rows).map(|_| Some(prefix_str.to_string())).collect();
74+
75+
if is_string_view {
76+
ColumnarValue::Array(Arc::new(StringViewArray::from(strings)))
77+
} else {
78+
ColumnarValue::Array(Arc::new(StringArray::from(strings)))
79+
}
80+
}
81+
82+
fn criterion_benchmark(c: &mut Criterion) {
83+
let starts_with = datafusion_functions::string::starts_with();
84+
let n_rows = 8192;
85+
let str_len = 128;
86+
let prefix_str = "xyz"; // A pattern that likely won't match
87+
88+
// Benchmark: StringArray with scalar prefix (the optimized path)
89+
let str_array = gen_string_array(n_rows, str_len, false);
90+
let scalar_prefix = gen_scalar_prefix(prefix_str, false);
91+
let arg_fields = vec![
92+
Field::new("a", DataType::Utf8, true).into(),
93+
Field::new("b", DataType::Utf8, true).into(),
94+
];
95+
let return_field = Field::new("f", DataType::Boolean, true).into();
96+
let config_options = Arc::new(ConfigOptions::default());
97+
98+
c.bench_function("starts_with_StringArray_scalar_prefix", |b| {
99+
b.iter(|| {
100+
black_box(starts_with.invoke_with_args(ScalarFunctionArgs {
101+
args: vec![str_array.clone(), scalar_prefix.clone()],
102+
arg_fields: arg_fields.clone(),
103+
number_rows: n_rows,
104+
return_field: Arc::clone(&return_field),
105+
config_options: Arc::clone(&config_options),
106+
}))
107+
})
108+
});
109+
110+
// Benchmark: StringArray with array prefix (for comparison)
111+
let array_prefix = gen_array_prefix(prefix_str, n_rows, false);
112+
c.bench_function("starts_with_StringArray_array_prefix", |b| {
113+
b.iter(|| {
114+
black_box(starts_with.invoke_with_args(ScalarFunctionArgs {
115+
args: vec![str_array.clone(), array_prefix.clone()],
116+
arg_fields: arg_fields.clone(),
117+
number_rows: n_rows,
118+
return_field: Arc::clone(&return_field),
119+
config_options: Arc::clone(&config_options),
120+
}))
121+
})
122+
});
123+
124+
// Benchmark: StringViewArray with scalar prefix (the optimized path)
125+
let str_view_array = gen_string_array(n_rows, str_len, true);
126+
let scalar_prefix_view = gen_scalar_prefix(prefix_str, true);
127+
let arg_fields_view = vec![
128+
Field::new("a", DataType::Utf8View, true).into(),
129+
Field::new("b", DataType::Utf8View, true).into(),
130+
];
131+
132+
c.bench_function("starts_with_StringViewArray_scalar_prefix", |b| {
133+
b.iter(|| {
134+
black_box(starts_with.invoke_with_args(ScalarFunctionArgs {
135+
args: vec![str_view_array.clone(), scalar_prefix_view.clone()],
136+
arg_fields: arg_fields_view.clone(),
137+
number_rows: n_rows,
138+
return_field: Arc::clone(&return_field),
139+
config_options: Arc::clone(&config_options),
140+
}))
141+
})
142+
});
143+
144+
// Benchmark: StringViewArray with array prefix (for comparison)
145+
let array_prefix_view = gen_array_prefix(prefix_str, n_rows, true);
146+
c.bench_function("starts_with_StringViewArray_array_prefix", |b| {
147+
b.iter(|| {
148+
black_box(starts_with.invoke_with_args(ScalarFunctionArgs {
149+
args: vec![str_view_array.clone(), array_prefix_view.clone()],
150+
arg_fields: arg_fields_view.clone(),
151+
number_rows: n_rows,
152+
return_field: Arc::clone(&return_field),
153+
config_options: Arc::clone(&config_options),
154+
}))
155+
})
156+
});
157+
158+
// Benchmark different string lengths with scalar prefix
159+
for str_len in [8, 32, 128, 512] {
160+
let str_array = gen_string_array(n_rows, str_len, true);
161+
let scalar_prefix = gen_scalar_prefix(prefix_str, true);
162+
let arg_fields = vec![
163+
Field::new("a", DataType::Utf8View, true).into(),
164+
Field::new("b", DataType::Utf8View, true).into(),
165+
];
166+
167+
c.bench_function(
168+
&format!("starts_with_StringViewArray_scalar_strlen_{str_len}"),
169+
|b| {
170+
b.iter(|| {
171+
black_box(starts_with.invoke_with_args(ScalarFunctionArgs {
172+
args: vec![str_array.clone(), scalar_prefix.clone()],
173+
arg_fields: arg_fields.clone(),
174+
number_rows: n_rows,
175+
return_field: Arc::clone(&return_field),
176+
config_options: Arc::clone(&config_options),
177+
}))
178+
})
179+
},
180+
);
181+
}
182+
}
183+
184+
criterion_group!(benches, criterion_benchmark);
185+
criterion_main!(benches);

0 commit comments

Comments
 (0)