Skip to content

Commit 94709dc

Browse files
authored
perf: improve performance of string replace (#19530)
## 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. --> Use a reusable String buffer instead of allocating a new String for each row. This optimization achieves 17-32% performance improvement across different string types and sizes by avoiding per-row allocations. Benchmark results: | Benchmark | Array Size | String Length | Baseline (µs) | Optimized (µs) | Improvement | |---------------|------------|---------------|---------------|----------------|-------------| | string_view | 1024 | 32 | 32.53 | 22.32 | 31.4% faster| | string | 1024 | 32 | 31.89 | 21.49 | 32.6% faster| | large_string | 1024 | 32 | 31.75 | 22.01 | 30.7% faster| | string_view | 1024 | 128 | 49.51 | 36.11 | 27.1% faster| | string | 1024 | 128 | 48.91 | 34.90 | 28.6% faster| | large_string | 1024 | 128 | 49.78 | 35.42 | 28.8% faster| | string_view | 4096 | 32 | 133.67 | 95.93 | 28.2% faster| | string | 4096 | 32 | 131.48 | 91.73 | 30.2% faster| | large_string | 4096 | 32 | 129.61 | 92.82 | 28.4% faster| | string_view | 4096 | 128 | 191.50 | 153.74 | 19.7% faster| | string | 4096 | 128 | 185.27 | 149.37 | 19.4% faster| | large_string | 4096 | 128 | 187.82 | 154.32 | 17.8% faster| ## 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 bd10f27 commit 94709dc

File tree

3 files changed

+268
-15
lines changed

3 files changed

+268
-15
lines changed

datafusion/functions/Cargo.toml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,11 @@ harness = false
210210
name = "repeat"
211211
required-features = ["string_expressions"]
212212

213+
[[bench]]
214+
harness = false
215+
name = "replace"
216+
required-features = ["string_expressions"]
217+
213218
[[bench]]
214219
harness = false
215220
name = "random"
Lines changed: 193 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,193 @@
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::OffsetSizeTrait;
21+
use arrow::datatypes::{DataType, Field};
22+
use arrow::util::bench_util::{
23+
create_string_array_with_len, create_string_view_array_with_len,
24+
};
25+
use criterion::{Criterion, SamplingMode, criterion_group, criterion_main};
26+
use datafusion_common::DataFusionError;
27+
use datafusion_common::config::ConfigOptions;
28+
use datafusion_expr::{ColumnarValue, ScalarFunctionArgs};
29+
use datafusion_functions::string;
30+
use std::hint::black_box;
31+
use std::sync::Arc;
32+
use std::time::Duration;
33+
34+
fn create_args<O: OffsetSizeTrait>(
35+
size: usize,
36+
str_len: usize,
37+
force_view_types: bool,
38+
from_len: usize,
39+
to_len: usize,
40+
) -> Vec<ColumnarValue> {
41+
if force_view_types {
42+
let string_array =
43+
Arc::new(create_string_view_array_with_len(size, 0.1, str_len, false));
44+
let from_array = Arc::new(create_string_view_array_with_len(
45+
size, 0.1, from_len, false,
46+
));
47+
let to_array =
48+
Arc::new(create_string_view_array_with_len(size, 0.1, to_len, false));
49+
vec![
50+
ColumnarValue::Array(string_array),
51+
ColumnarValue::Array(from_array),
52+
ColumnarValue::Array(to_array),
53+
]
54+
} else {
55+
let string_array =
56+
Arc::new(create_string_array_with_len::<O>(size, 0.1, str_len));
57+
let from_array = Arc::new(create_string_array_with_len::<O>(size, 0.1, from_len));
58+
let to_array = Arc::new(create_string_array_with_len::<O>(size, 0.1, to_len));
59+
60+
vec![
61+
ColumnarValue::Array(string_array),
62+
ColumnarValue::Array(from_array),
63+
ColumnarValue::Array(to_array),
64+
]
65+
}
66+
}
67+
68+
fn invoke_replace_with_args(
69+
args: Vec<ColumnarValue>,
70+
number_rows: usize,
71+
) -> Result<ColumnarValue, DataFusionError> {
72+
let arg_fields = args
73+
.iter()
74+
.enumerate()
75+
.map(|(idx, arg)| Field::new(format!("arg_{idx}"), arg.data_type(), true).into())
76+
.collect::<Vec<_>>();
77+
let config_options = Arc::new(ConfigOptions::default());
78+
79+
string::replace().invoke_with_args(ScalarFunctionArgs {
80+
args,
81+
arg_fields,
82+
number_rows,
83+
return_field: Field::new("f", DataType::Utf8, true).into(),
84+
config_options: Arc::clone(&config_options),
85+
})
86+
}
87+
88+
fn criterion_benchmark(c: &mut Criterion) {
89+
for size in [1024, 4096] {
90+
let mut group = c.benchmark_group(format!("replace size={size}"));
91+
group.sampling_mode(SamplingMode::Flat);
92+
group.sample_size(10);
93+
group.measurement_time(Duration::from_secs(10));
94+
95+
// ASCII single character replacement (fast path)
96+
let str_len = 32;
97+
let args = create_args::<i32>(size, str_len, false, 1, 1);
98+
group.bench_function(
99+
format!("replace_string_ascii_single [size={size}, str_len={str_len}]"),
100+
|b| {
101+
b.iter(|| {
102+
let args_cloned = args.clone();
103+
black_box(invoke_replace_with_args(args_cloned, size))
104+
})
105+
},
106+
);
107+
108+
// Multi-character strings (general path)
109+
let args = create_args::<i32>(size, str_len, true, 3, 5);
110+
group.bench_function(
111+
format!("replace_string_view [size={size}, str_len={str_len}]"),
112+
|b| {
113+
b.iter(|| {
114+
let args_cloned = args.clone();
115+
black_box(invoke_replace_with_args(args_cloned, size))
116+
})
117+
},
118+
);
119+
120+
let args = create_args::<i32>(size, str_len, false, 3, 5);
121+
group.bench_function(
122+
format!("replace_string [size={size}, str_len={str_len}]"),
123+
|b| {
124+
b.iter(|| {
125+
let args_cloned = args.clone();
126+
black_box(invoke_replace_with_args(args_cloned, size))
127+
})
128+
},
129+
);
130+
131+
let args = create_args::<i64>(size, str_len, false, 3, 5);
132+
group.bench_function(
133+
format!("replace_large_string [size={size}, str_len={str_len}]"),
134+
|b| {
135+
b.iter(|| {
136+
let args_cloned = args.clone();
137+
black_box(invoke_replace_with_args(args_cloned, size))
138+
})
139+
},
140+
);
141+
142+
// Larger strings
143+
let str_len = 128;
144+
let args = create_args::<i32>(size, str_len, false, 1, 1);
145+
group.bench_function(
146+
format!("replace_string_ascii_single [size={size}, str_len={str_len}]"),
147+
|b| {
148+
b.iter(|| {
149+
let args_cloned = args.clone();
150+
black_box(invoke_replace_with_args(args_cloned, size))
151+
})
152+
},
153+
);
154+
155+
let args = create_args::<i32>(size, str_len, true, 3, 5);
156+
group.bench_function(
157+
format!("replace_string_view [size={size}, str_len={str_len}]"),
158+
|b| {
159+
b.iter(|| {
160+
let args_cloned = args.clone();
161+
black_box(invoke_replace_with_args(args_cloned, size))
162+
})
163+
},
164+
);
165+
166+
let args = create_args::<i32>(size, str_len, false, 3, 5);
167+
group.bench_function(
168+
format!("replace_string [size={size}, str_len={str_len}]"),
169+
|b| {
170+
b.iter(|| {
171+
let args_cloned = args.clone();
172+
black_box(invoke_replace_with_args(args_cloned, size))
173+
})
174+
},
175+
);
176+
177+
let args = create_args::<i64>(size, str_len, false, 3, 5);
178+
group.bench_function(
179+
format!("replace_large_string [size={size}, str_len={str_len}]"),
180+
|b| {
181+
b.iter(|| {
182+
let args_cloned = args.clone();
183+
black_box(invoke_replace_with_args(args_cloned, size))
184+
})
185+
},
186+
);
187+
188+
group.finish();
189+
}
190+
}
191+
192+
criterion_group!(benches, criterion_benchmark);
193+
criterion_main!(benches);

datafusion/functions/src/string/replace.rs

Lines changed: 70 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
use std::any::Any;
1919
use std::sync::Arc;
2020

21-
use arrow::array::{ArrayRef, GenericStringArray, OffsetSizeTrait, StringArray};
21+
use arrow::array::{ArrayRef, GenericStringBuilder, OffsetSizeTrait};
2222
use arrow::datatypes::DataType;
2323

2424
use crate::utils::{make_scalar_function, utf8_to_str_type};
@@ -165,17 +165,25 @@ fn replace_view(args: &[ArrayRef]) -> Result<ArrayRef> {
165165
let from_array = as_string_view_array(&args[1])?;
166166
let to_array = as_string_view_array(&args[2])?;
167167

168-
let result = string_array
168+
let mut builder = GenericStringBuilder::<i32>::new();
169+
let mut buffer = String::new();
170+
171+
for ((string, from), to) in string_array
169172
.iter()
170173
.zip(from_array.iter())
171174
.zip(to_array.iter())
172-
.map(|((string, from), to)| match (string, from, to) {
173-
(Some(string), Some(from), Some(to)) => Some(string.replace(from, to)),
174-
_ => None,
175-
})
176-
.collect::<StringArray>();
175+
{
176+
match (string, from, to) {
177+
(Some(string), Some(from), Some(to)) => {
178+
buffer.clear();
179+
replace_into_string(&mut buffer, string, from, to);
180+
builder.append_value(&buffer);
181+
}
182+
_ => builder.append_null(),
183+
}
184+
}
177185

178-
Ok(Arc::new(result) as ArrayRef)
186+
Ok(Arc::new(builder.finish()) as ArrayRef)
179187
}
180188

181189
/// Replaces all occurrences in string of substring from with substring to.
@@ -185,17 +193,64 @@ fn replace<T: OffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef> {
185193
let from_array = as_generic_string_array::<T>(&args[1])?;
186194
let to_array = as_generic_string_array::<T>(&args[2])?;
187195

188-
let result = string_array
196+
let mut builder = GenericStringBuilder::<T>::new();
197+
let mut buffer = String::new();
198+
199+
for ((string, from), to) in string_array
189200
.iter()
190201
.zip(from_array.iter())
191202
.zip(to_array.iter())
192-
.map(|((string, from), to)| match (string, from, to) {
193-
(Some(string), Some(from), Some(to)) => Some(string.replace(from, to)),
194-
_ => None,
195-
})
196-
.collect::<GenericStringArray<T>>();
203+
{
204+
match (string, from, to) {
205+
(Some(string), Some(from), Some(to)) => {
206+
buffer.clear();
207+
replace_into_string(&mut buffer, string, from, to);
208+
builder.append_value(&buffer);
209+
}
210+
_ => builder.append_null(),
211+
}
212+
}
197213

198-
Ok(Arc::new(result) as ArrayRef)
214+
Ok(Arc::new(builder.finish()) as ArrayRef)
215+
}
216+
217+
/// Helper function to perform string replacement into a reusable String buffer
218+
#[inline]
219+
fn replace_into_string(buffer: &mut String, string: &str, from: &str, to: &str) {
220+
if from.is_empty() {
221+
// When from is empty, insert 'to' at the beginning, between each character, and at the end
222+
// This matches the behavior of str::replace()
223+
buffer.push_str(to);
224+
for ch in string.chars() {
225+
buffer.push(ch);
226+
buffer.push_str(to);
227+
}
228+
return;
229+
}
230+
231+
// Fast path for replacing a single ASCII character with another single ASCII character
232+
// This matches Rust's str::replace() optimization and enables vectorization
233+
if let ([from_byte], [to_byte]) = (from.as_bytes(), to.as_bytes())
234+
&& from_byte.is_ascii()
235+
&& to_byte.is_ascii()
236+
{
237+
// SAFETY: We're replacing ASCII with ASCII, which preserves UTF-8 validity
238+
let replaced: Vec<u8> = string
239+
.as_bytes()
240+
.iter()
241+
.map(|b| if *b == *from_byte { *to_byte } else { *b })
242+
.collect();
243+
buffer.push_str(unsafe { std::str::from_utf8_unchecked(&replaced) });
244+
return;
245+
}
246+
247+
let mut last_end = 0;
248+
for (start, _part) in string.match_indices(from) {
249+
buffer.push_str(&string[last_end..start]);
250+
buffer.push_str(to);
251+
last_end = start + from.len();
252+
}
253+
buffer.push_str(&string[last_end..]);
199254
}
200255

201256
#[cfg(test)]

0 commit comments

Comments
 (0)