Skip to content

Commit 56a2be1

Browse files
authored
perf: optimize regexp_count to avoid String allocation when start position is provided (#19553)
## 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. --> ## 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. --> Replace `.chars().skip().collect::<String>()` with zero-copy string slicing using `char_indices()` to find the byte offset, then slice with `&value[byte_offset..]`. This eliminates unnecessary String allocation per row when a start position is specified. Changes: - Use char_indices().nth() to find byte offset for start position (1-based) - Use string slicing &value[byte_offset..] instead of collecting chars - Added benchmark to measure performance improvements Optimization: - Before: Allocated new String via .collect() for each row with start position - After: Uses zero-copy string slice Benchmark results: - size=1024, str_len=32: 96.361 µs -> 41.458 µs (57.0% faster, 2.3x speedup) - size=1024, str_len=128: 210.16 µs -> 56.064 µs (73.3% faster, 3.7x speedup) - size=4096, str_len=32: 376.90 µs -> 162.98 µs (56.8% faster, 2.3x speedup) - size=4096, str_len=128: 855.68 µs -> 263.61 µs (69.2% faster, 3.2x speedup) The optimization shows greater improvements for longer strings (up to 73% faster) since string slicing is O(1) regardless of length, while the previous approach had allocation costs that grew with string length. ## 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)? --> ## 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. -->
1 parent 9690f95 commit 56a2be1

File tree

3 files changed

+133
-2
lines changed

3 files changed

+133
-2
lines changed

datafusion/functions/Cargo.toml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,11 @@ harness = false
275275
name = "ends_with"
276276
required-features = ["string_expressions"]
277277

278+
[[bench]]
279+
harness = false
280+
name = "regexp_count"
281+
required-features = ["regex_expressions"]
282+
278283
[[bench]]
279284
harness = false
280285
name = "crypto"
Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
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::Int64Array;
21+
use arrow::array::OffsetSizeTrait;
22+
use arrow::datatypes::{DataType, Field};
23+
use arrow::util::bench_util::create_string_array_with_len;
24+
use criterion::{Criterion, SamplingMode, criterion_group, criterion_main};
25+
use datafusion_common::config::ConfigOptions;
26+
use datafusion_common::{DataFusionError, ScalarValue};
27+
use datafusion_expr::{ColumnarValue, ScalarFunctionArgs};
28+
use datafusion_functions::regex;
29+
use std::hint::black_box;
30+
use std::sync::Arc;
31+
use std::time::Duration;
32+
33+
fn create_args<O: OffsetSizeTrait>(
34+
size: usize,
35+
str_len: usize,
36+
with_start: bool,
37+
) -> Vec<ColumnarValue> {
38+
let string_array = Arc::new(create_string_array_with_len::<O>(size, 0.1, str_len));
39+
40+
// Use a simple pattern that matches common characters
41+
let pattern = ColumnarValue::Scalar(ScalarValue::Utf8(Some("a".to_string())));
42+
43+
if with_start {
44+
// Test with start position (this is where the optimization matters)
45+
let start_array = Arc::new(Int64Array::from(
46+
(0..size).map(|i| (i % 10 + 1) as i64).collect::<Vec<_>>(),
47+
));
48+
vec![
49+
ColumnarValue::Array(string_array),
50+
pattern,
51+
ColumnarValue::Array(start_array),
52+
]
53+
} else {
54+
vec![ColumnarValue::Array(string_array), pattern]
55+
}
56+
}
57+
58+
fn invoke_regexp_count_with_args(
59+
args: Vec<ColumnarValue>,
60+
number_rows: usize,
61+
) -> Result<ColumnarValue, DataFusionError> {
62+
let arg_fields = args
63+
.iter()
64+
.enumerate()
65+
.map(|(idx, arg)| Field::new(format!("arg_{idx}"), arg.data_type(), true).into())
66+
.collect::<Vec<_>>();
67+
let config_options = Arc::new(ConfigOptions::default());
68+
69+
regex::regexp_count().invoke_with_args(ScalarFunctionArgs {
70+
args,
71+
arg_fields,
72+
number_rows,
73+
return_field: Field::new("f", DataType::Int64, true).into(),
74+
config_options: Arc::clone(&config_options),
75+
})
76+
}
77+
78+
fn criterion_benchmark(c: &mut Criterion) {
79+
for size in [1024, 4096] {
80+
let mut group = c.benchmark_group(format!("regexp_count size={size}"));
81+
group.sampling_mode(SamplingMode::Flat);
82+
group.sample_size(10);
83+
group.measurement_time(Duration::from_secs(10));
84+
85+
// Test without start position (no optimization impact)
86+
for str_len in [32, 128] {
87+
let args = create_args::<i32>(size, str_len, false);
88+
group.bench_function(
89+
format!("regexp_count_no_start [size={size}, str_len={str_len}]"),
90+
|b| {
91+
b.iter(|| {
92+
let args_cloned = args.clone();
93+
black_box(invoke_regexp_count_with_args(args_cloned, size))
94+
})
95+
},
96+
);
97+
}
98+
99+
// Test with start position (optimization should help here)
100+
for str_len in [32, 128] {
101+
let args = create_args::<i32>(size, str_len, true);
102+
group.bench_function(
103+
format!("regexp_count_with_start [size={size}, str_len={str_len}]"),
104+
|b| {
105+
b.iter(|| {
106+
let args_cloned = args.clone();
107+
black_box(invoke_regexp_count_with_args(args_cloned, size))
108+
})
109+
},
110+
);
111+
}
112+
113+
group.finish();
114+
}
115+
}
116+
117+
criterion_group!(benches, criterion_benchmark);
118+
criterion_main!(benches);

datafusion/functions/src/regex/regexpcount.rs

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -569,8 +569,16 @@ fn count_matches(
569569
));
570570
}
571571

572-
let find_slice = value.chars().skip(start as usize - 1).collect::<String>();
573-
let count = pattern.find_iter(find_slice.as_str()).count();
572+
// Find the byte offset for the start position (1-based character index)
573+
let byte_offset = value
574+
.char_indices()
575+
.nth((start as usize).saturating_sub(1))
576+
.map(|(idx, _)| idx)
577+
.unwrap_or(value.len());
578+
579+
// Use string slicing instead of collecting chars into a new String
580+
let find_slice = &value[byte_offset..];
581+
let count = pattern.find_iter(find_slice).count();
574582
Ok(count as i64)
575583
} else {
576584
let count = pattern.find_iter(value).count();

0 commit comments

Comments
 (0)