Skip to content

Commit 166ef81

Browse files
authored
Perf: Optimize substring_index via single-byte fast path and direct indexing (#19590)
## 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. --> ## 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. --> This PR improves the performance of the `substring_index` function by optimizing delimiter search and substring extraction: - Single-byte fast path: introduces a specialized byte-based search for single-byte delimiters (e.g. `.`, `,`), avoiding UTF-8 pattern matching overhead. - Efficient index discovery: replaces the split-and-sum-length approach with direct index location using `match_indices` / `rmatch_indices`. ## 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. --> - Added a fast path for `delimiter.len() == 1` using byte-based search. - Refactored the general path to use `match_indices` and `rmatch_indices` for more efficient positioning. ### Benchmarks - Single-byte delimiter benchmarks show ~2–3× speedup across batch sizes. - Multi-byte delimiters see a consistent ~10–15% improvement. ``` group main_substrindex perf_substrindex ----- ---------------- ---------------- substr_index/substr_index_10000_long_delimiter 1.12 548.2±18.39µs ? ?/sec 1.00 488.4±15.62µs ? ?/sec substr_index/substr_index_10000_single_delimiter 2.14 543.4±15.12µs ? ?/sec 1.00 254.0±7.80µs ? ?/sec substr_index/substr_index_1000_long_delimiter 1.12 43.1±1.63µs ? ?/sec 1.00 38.6±2.03µs ? ?/sec substr_index/substr_index_1000_single_delimiter 3.51 46.4±2.21µs ? ?/sec 1.00 13.2±0.99µs ? ?/sec substr_index/substr_index_100_long_delimiter 1.01 3.7±0.18µs ? ?/sec 1.00 3.7±0.20µs ? ?/sec substr_index/substr_index_100_single_delimiter 2.15 3.6±0.14µs ? ?/sec 1.00 1675.9±79.15ns ? ?/sec ``` ## Are these changes tested? - Yes, Existing unit tests pass. - New benchmarks added to verify performance improvement. <!-- 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? No. <!-- 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 e8196f4 commit 166ef81

File tree

2 files changed

+130
-64
lines changed

2 files changed

+130
-64
lines changed

datafusion/functions/benches/substr_index.rs

Lines changed: 86 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,10 @@ where
5050
}
5151
}
5252

53-
fn data() -> (StringArray, StringArray, Int64Array) {
53+
fn data(
54+
batch_size: usize,
55+
single_char_delimiter: bool,
56+
) -> (StringArray, StringArray, Int64Array) {
5457
let dist = Filter {
5558
dist: Uniform::new(-4, 5),
5659
test: |x: &i64| x != &0,
@@ -60,19 +63,39 @@ fn data() -> (StringArray, StringArray, Int64Array) {
6063
let mut delimiters: Vec<String> = vec![];
6164
let mut counts: Vec<i64> = vec![];
6265

63-
for _ in 0..1000 {
66+
for _ in 0..batch_size {
6467
let length = rng.random_range(20..50);
65-
let text: String = (&mut rng)
68+
let base: String = (&mut rng)
6669
.sample_iter(&Alphanumeric)
6770
.take(length)
6871
.map(char::from)
6972
.collect();
70-
let char = rng.random_range(0..text.len());
71-
let delimiter = &text.chars().nth(char).unwrap();
73+
74+
let (string_value, delimiter): (String, String) = if single_char_delimiter {
75+
let char_idx = rng.random_range(0..base.chars().count());
76+
let delimiter = base.chars().nth(char_idx).unwrap().to_string();
77+
(base, delimiter)
78+
} else {
79+
let long_delimiters = ["|||", "***", "&&&", "###", "@@@", "$$$"];
80+
let delimiter =
81+
long_delimiters[rng.random_range(0..long_delimiters.len())].to_string();
82+
83+
let delimiter_count = rng.random_range(1..4);
84+
let mut result = String::new();
85+
86+
for i in 0..delimiter_count {
87+
result.push_str(&base);
88+
if i < delimiter_count - 1 {
89+
result.push_str(&delimiter);
90+
}
91+
}
92+
(result, delimiter)
93+
};
94+
7295
let count = rng.sample(dist.dist.unwrap());
7396

74-
strings.push(text);
75-
delimiters.push(delimiter.to_string());
97+
strings.push(string_value);
98+
delimiters.push(delimiter);
7699
counts.push(count);
77100
}
78101

@@ -83,38 +106,63 @@ fn data() -> (StringArray, StringArray, Int64Array) {
83106
)
84107
}
85108

86-
fn criterion_benchmark(c: &mut Criterion) {
87-
c.bench_function("substr_index_array_array_1000", |b| {
88-
let (strings, delimiters, counts) = data();
89-
let batch_len = counts.len();
90-
let strings = ColumnarValue::Array(Arc::new(strings) as ArrayRef);
91-
let delimiters = ColumnarValue::Array(Arc::new(delimiters) as ArrayRef);
92-
let counts = ColumnarValue::Array(Arc::new(counts) as ArrayRef);
93-
94-
let args = vec![strings, delimiters, counts];
95-
let arg_fields = args
96-
.iter()
97-
.enumerate()
98-
.map(|(idx, arg)| {
99-
Field::new(format!("arg_{idx}"), arg.data_type(), true).into()
100-
})
101-
.collect::<Vec<_>>();
102-
let config_options = Arc::new(ConfigOptions::default());
103-
104-
b.iter(|| {
105-
black_box(
106-
substr_index()
107-
.invoke_with_args(ScalarFunctionArgs {
108-
args: args.clone(),
109-
arg_fields: arg_fields.clone(),
110-
number_rows: batch_len,
111-
return_field: Field::new("f", DataType::Utf8, true).into(),
112-
config_options: Arc::clone(&config_options),
113-
})
114-
.expect("substr_index should work on valid values"),
115-
)
109+
fn run_benchmark(
110+
b: &mut criterion::Bencher,
111+
strings: StringArray,
112+
delimiters: StringArray,
113+
counts: Int64Array,
114+
batch_size: usize,
115+
) {
116+
let strings = ColumnarValue::Array(Arc::new(strings) as ArrayRef);
117+
let delimiters = ColumnarValue::Array(Arc::new(delimiters) as ArrayRef);
118+
let counts = ColumnarValue::Array(Arc::new(counts) as ArrayRef);
119+
120+
let args = vec![strings, delimiters, counts];
121+
let arg_fields = args
122+
.iter()
123+
.enumerate()
124+
.map(|(idx, arg)| {
125+
Field::new(format!("arg_{idx}"), arg.data_type().clone(), true).into()
116126
})
117-
});
127+
.collect::<Vec<_>>();
128+
let config_options = Arc::new(ConfigOptions::default());
129+
130+
b.iter(|| {
131+
black_box(
132+
substr_index()
133+
.invoke_with_args(ScalarFunctionArgs {
134+
args: args.clone(),
135+
arg_fields: arg_fields.clone(),
136+
number_rows: batch_size,
137+
return_field: Field::new("f", DataType::Utf8, true).into(),
138+
config_options: Arc::clone(&config_options),
139+
})
140+
.expect("substr_index should work on valid values"),
141+
)
142+
})
143+
}
144+
145+
fn criterion_benchmark(c: &mut Criterion) {
146+
let mut group = c.benchmark_group("substr_index");
147+
148+
let batch_sizes = [100, 1000, 10_000];
149+
150+
for batch_size in batch_sizes {
151+
group.bench_function(
152+
format!("substr_index_{batch_size}_single_delimiter"),
153+
|b| {
154+
let (strings, delimiters, counts) = data(batch_size, true);
155+
run_benchmark(b, strings, delimiters, counts, batch_size);
156+
},
157+
);
158+
159+
group.bench_function(format!("substr_index_{batch_size}_long_delimiter"), |b| {
160+
let (strings, delimiters, counts) = data(batch_size, false);
161+
run_benchmark(b, strings, delimiters, counts, batch_size);
162+
});
163+
}
164+
165+
group.finish();
118166
}
119167

120168
criterion_group!(benches, criterion_benchmark);

datafusion/functions/src/unicode/substrindex.rs

Lines changed: 44 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@ use std::any::Any;
1919
use std::sync::Arc;
2020

2121
use arrow::array::{
22-
ArrayAccessor, ArrayIter, ArrayRef, ArrowPrimitiveType, AsArray, OffsetSizeTrait,
23-
PrimitiveArray, StringBuilder,
22+
ArrayAccessor, ArrayIter, ArrayRef, ArrowPrimitiveType, AsArray,
23+
GenericStringBuilder, OffsetSizeTrait, PrimitiveArray,
2424
};
2525
use arrow::datatypes::{DataType, Int32Type, Int64Type};
2626

@@ -182,7 +182,8 @@ fn substr_index_general<
182182
where
183183
T::Native: OffsetSizeTrait,
184184
{
185-
let mut builder = StringBuilder::new();
185+
let num_rows = string_array.len();
186+
let mut builder = GenericStringBuilder::<T::Native>::with_capacity(num_rows, 0);
186187
let string_iter = ArrayIter::new(string_array);
187188
let delimiter_array_iter = ArrayIter::new(delimiter_array);
188189
let count_array_iter = ArrayIter::new(count_array);
@@ -198,31 +199,49 @@ where
198199
}
199200

200201
let occurrences = usize::try_from(n.unsigned_abs()).unwrap_or(usize::MAX);
201-
let length = if n > 0 {
202-
let split = string.split(delimiter);
203-
split
204-
.take(occurrences)
205-
.map(|s| s.len() + delimiter.len())
206-
.sum::<usize>()
207-
- delimiter.len()
208-
} else {
209-
let split = string.rsplit(delimiter);
210-
split
211-
.take(occurrences)
212-
.map(|s| s.len() + delimiter.len())
213-
.sum::<usize>()
214-
- delimiter.len()
215-
};
216-
if n > 0 {
217-
match string.get(..length) {
218-
Some(substring) => builder.append_value(substring),
219-
None => builder.append_null(),
202+
let result_idx = if delimiter.len() == 1 {
203+
// Fast path: use byte-level search for single-character delimiters
204+
let d_byte = delimiter.as_bytes()[0];
205+
let bytes = string.as_bytes();
206+
207+
if n > 0 {
208+
bytes
209+
.iter()
210+
.enumerate()
211+
.filter(|&(_, &b)| b == d_byte)
212+
.nth(occurrences - 1)
213+
.map(|(idx, _)| idx)
214+
} else {
215+
bytes
216+
.iter()
217+
.enumerate()
218+
.rev()
219+
.filter(|&(_, &b)| b == d_byte)
220+
.nth(occurrences - 1)
221+
.map(|(idx, _)| idx + 1)
220222
}
223+
} else if n > 0 {
224+
// Multi-byte path: forward search for n-th occurrence
225+
string
226+
.match_indices(delimiter)
227+
.nth(occurrences - 1)
228+
.map(|(idx, _)| idx)
221229
} else {
222-
match string.get(string.len().saturating_sub(length)..) {
223-
Some(substring) => builder.append_value(substring),
224-
None => builder.append_null(),
230+
// Multi-byte path: backward search for n-th occurrence from the right
231+
string
232+
.rmatch_indices(delimiter)
233+
.nth(occurrences - 1)
234+
.map(|(idx, _)| idx + delimiter.len())
235+
};
236+
match result_idx {
237+
Some(idx) => {
238+
if n > 0 {
239+
builder.append_value(&string[..idx]);
240+
} else {
241+
builder.append_value(&string[idx..]);
242+
}
225243
}
244+
None => builder.append_value(string),
226245
}
227246
}
228247
_ => builder.append_null(),
@@ -328,7 +347,6 @@ mod tests {
328347
Utf8,
329348
StringArray
330349
);
331-
332350
Ok(())
333351
}
334352
}

0 commit comments

Comments
 (0)