Skip to content

Commit 9690f95

Browse files
authored
perf: improve performance of lpad/rpad by reusing buffers (#19558)
Optimized lpad and rpad functions to eliminate per-row allocations by reusing buffers for graphemes and fill characters. The previous implementation allocated new Vec<&str> for graphemes and Vec<char> for fill characters on every row, which was inefficient. This optimization introduces reusable buffers that are allocated once and cleared/refilled for each row. Changes: - lpad: Added graphemes_buf and fill_chars_buf outside loops, clear and refill per row instead of allocating new Vec each time - rpad: Added graphemes_buf outside loops to reuse across iterations - Both functions now allocate buffers once and reuse them for all rows - Buffers are cleared and reused for each row via .clear() and .extend() Optimization impact: - For lpad with fill parameter: Eliminates 2 Vec allocations per row (graphemes + fill_chars) - For lpad without fill: Eliminates 1 Vec allocation per row (graphemes) - For rpad: Eliminates 1 Vec allocation per row (graphemes) This optimization is particularly effective for: - Large arrays with many rows - Strings with multiple graphemes (unicode characters) - Workloads with custom fill patterns Benchmark results comparing main vs optimized branch: lpad benchmarks: - size=1024, str_len=5, target=20: 116.53 µs -> 63.226 µs (45.7% faster) - size=1024, str_len=20, target=50: 314.07 µs -> 190.30 µs (39.4% faster) - size=4096, str_len=5, target=20: 467.35 µs -> 261.29 µs (44.1% faster) - size=4096, str_len=20, target=50: 1.2286 ms -> 754.24 µs (38.6% faster) rpad benchmarks: - size=1024, str_len=5, target=20: 113.89 µs -> 72.645 µs (36.2% faster) - size=1024, str_len=20, target=50: 313.68 µs -> 202.98 µs (35.3% faster) - size=4096, str_len=5, target=20: 456.08 µs -> 295.57 µs (35.2% faster) - size=4096, str_len=20, target=50: 1.2523 ms -> 818.47 µs (34.6% faster) Overall improvements: 35-46% faster across all workloads ## 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. --> ## 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 1704d1e commit 9690f95

File tree

3 files changed

+283
-102
lines changed

3 files changed

+283
-102
lines changed

datafusion/functions/benches/pad.rs

Lines changed: 236 additions & 78 deletions
Original file line numberDiff line numberDiff line change
@@ -15,20 +15,22 @@
1515
// specific language governing permissions and limitations
1616
// under the License.
1717

18-
use arrow::array::{ArrayRef, ArrowPrimitiveType, OffsetSizeTrait, PrimitiveArray};
18+
extern crate criterion;
19+
20+
use arrow::array::{ArrowPrimitiveType, OffsetSizeTrait, PrimitiveArray};
1921
use arrow::datatypes::{DataType, Field, Int64Type};
2022
use arrow::util::bench_util::{
2123
create_string_array_with_len, create_string_view_array_with_len,
2224
};
23-
use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main};
24-
use datafusion_common::DataFusionError;
25+
use criterion::{Criterion, SamplingMode, criterion_group, criterion_main};
2526
use datafusion_common::config::ConfigOptions;
2627
use datafusion_expr::{ColumnarValue, ScalarFunctionArgs};
27-
use datafusion_functions::unicode::{lpad, rpad};
28+
use datafusion_functions::unicode;
2829
use rand::Rng;
2930
use rand::distr::{Distribution, Uniform};
3031
use std::hint::black_box;
3132
use std::sync::Arc;
33+
use std::time::Duration;
3234

3335
struct Filter<Dist> {
3436
dist: Dist,
@@ -67,104 +69,260 @@ where
6769
.collect()
6870
}
6971

70-
fn create_args<O: OffsetSizeTrait>(
72+
/// Create args for pad benchmark
73+
fn create_pad_args<O: OffsetSizeTrait>(
7174
size: usize,
7275
str_len: usize,
73-
force_view_types: bool,
76+
target_len: usize,
77+
use_string_view: bool,
7478
) -> Vec<ColumnarValue> {
75-
let length_array = Arc::new(create_primitive_array::<Int64Type>(size, 0.0, str_len));
76-
77-
if !force_view_types {
78-
let string_array =
79-
Arc::new(create_string_array_with_len::<O>(size, 0.1, str_len));
80-
let fill_array = Arc::new(create_string_array_with_len::<O>(size, 0.1, str_len));
79+
let length_array =
80+
Arc::new(create_primitive_array::<Int64Type>(size, 0.0, target_len));
8181

82+
if use_string_view {
83+
let string_array = create_string_view_array_with_len(size, 0.1, str_len, false);
84+
let fill_array = create_string_view_array_with_len(size, 0.1, str_len, false);
8285
vec![
83-
ColumnarValue::Array(string_array),
84-
ColumnarValue::Array(Arc::clone(&length_array) as ArrayRef),
85-
ColumnarValue::Array(fill_array),
86+
ColumnarValue::Array(Arc::new(string_array)),
87+
ColumnarValue::Array(length_array),
88+
ColumnarValue::Array(Arc::new(fill_array)),
8689
]
8790
} else {
88-
let string_array =
89-
Arc::new(create_string_view_array_with_len(size, 0.1, str_len, false));
90-
let fill_array =
91-
Arc::new(create_string_view_array_with_len(size, 0.1, str_len, false));
92-
91+
let string_array = create_string_array_with_len::<O>(size, 0.1, str_len);
92+
let fill_array = create_string_array_with_len::<O>(size, 0.1, str_len);
9393
vec![
94-
ColumnarValue::Array(string_array),
95-
ColumnarValue::Array(Arc::clone(&length_array) as ArrayRef),
96-
ColumnarValue::Array(fill_array),
94+
ColumnarValue::Array(Arc::new(string_array)),
95+
ColumnarValue::Array(length_array),
96+
ColumnarValue::Array(Arc::new(fill_array)),
9797
]
9898
}
9999
}
100100

101-
#[expect(clippy::needless_pass_by_value)]
102-
fn invoke_pad_with_args(
103-
args: Vec<ColumnarValue>,
104-
number_rows: usize,
105-
left_pad: bool,
106-
) -> Result<ColumnarValue, DataFusionError> {
107-
let arg_fields = args
108-
.iter()
109-
.enumerate()
110-
.map(|(idx, arg)| Field::new(format!("arg_{idx}"), arg.data_type(), true).into())
111-
.collect::<Vec<_>>();
112-
let config_options = Arc::new(ConfigOptions::default());
113-
114-
let scalar_args = ScalarFunctionArgs {
115-
args: args.clone(),
116-
arg_fields,
117-
number_rows,
118-
return_field: Field::new("f", DataType::Utf8, true).into(),
119-
config_options: Arc::clone(&config_options),
120-
};
101+
fn criterion_benchmark(c: &mut Criterion) {
102+
for size in [1024, 4096] {
103+
let mut group = c.benchmark_group(format!("lpad size={size}"));
104+
group.sampling_mode(SamplingMode::Flat);
105+
group.sample_size(10);
106+
group.measurement_time(Duration::from_secs(10));
121107

122-
if left_pad {
123-
lpad().invoke_with_args(scalar_args)
124-
} else {
125-
rpad().invoke_with_args(scalar_args)
126-
}
127-
}
108+
// Utf8 type
109+
let args = create_pad_args::<i32>(size, 5, 20, false);
110+
let arg_fields = args
111+
.iter()
112+
.enumerate()
113+
.map(|(idx, arg)| {
114+
Field::new(format!("arg_{idx}"), arg.data_type(), true).into()
115+
})
116+
.collect::<Vec<_>>();
117+
let config_options = Arc::new(ConfigOptions::default());
128118

129-
fn criterion_benchmark(c: &mut Criterion) {
130-
for size in [1024, 2048] {
131-
let mut group = c.benchmark_group("lpad function");
119+
group.bench_function(
120+
format!("lpad utf8 [size={size}, str_len=5, target=20]"),
121+
|b| {
122+
b.iter(|| {
123+
let args_cloned = args.clone();
124+
black_box(unicode::lpad().invoke_with_args(ScalarFunctionArgs {
125+
args: args_cloned,
126+
arg_fields: arg_fields.clone(),
127+
number_rows: size,
128+
return_field: Field::new("f", DataType::Utf8, true).into(),
129+
config_options: Arc::clone(&config_options),
130+
}))
131+
})
132+
},
133+
);
132134

133-
let args = create_args::<i32>(size, 32, false);
135+
// StringView type
136+
let args = create_pad_args::<i32>(size, 5, 20, true);
137+
let arg_fields = args
138+
.iter()
139+
.enumerate()
140+
.map(|(idx, arg)| {
141+
Field::new(format!("arg_{idx}"), arg.data_type(), true).into()
142+
})
143+
.collect::<Vec<_>>();
134144

135-
group.bench_function(BenchmarkId::new("utf8 type", size), |b| {
136-
b.iter(|| black_box(invoke_pad_with_args(args.clone(), size, true).unwrap()))
137-
});
145+
group.bench_function(
146+
format!("lpad stringview [size={size}, str_len=5, target=20]"),
147+
|b| {
148+
b.iter(|| {
149+
let args_cloned = args.clone();
150+
black_box(unicode::lpad().invoke_with_args(ScalarFunctionArgs {
151+
args: args_cloned,
152+
arg_fields: arg_fields.clone(),
153+
number_rows: size,
154+
return_field: Field::new("f", DataType::Utf8View, true).into(),
155+
config_options: Arc::clone(&config_options),
156+
}))
157+
})
158+
},
159+
);
138160

139-
let args = create_args::<i64>(size, 32, false);
140-
group.bench_function(BenchmarkId::new("largeutf8 type", size), |b| {
141-
b.iter(|| black_box(invoke_pad_with_args(args.clone(), size, true).unwrap()))
142-
});
161+
// Utf8 type with longer strings
162+
let args = create_pad_args::<i32>(size, 20, 50, false);
163+
let arg_fields = args
164+
.iter()
165+
.enumerate()
166+
.map(|(idx, arg)| {
167+
Field::new(format!("arg_{idx}"), arg.data_type(), true).into()
168+
})
169+
.collect::<Vec<_>>();
143170

144-
let args = create_args::<i32>(size, 32, true);
145-
group.bench_function(BenchmarkId::new("stringview type", size), |b| {
146-
b.iter(|| black_box(invoke_pad_with_args(args.clone(), size, true).unwrap()))
147-
});
171+
group.bench_function(
172+
format!("lpad utf8 [size={size}, str_len=20, target=50]"),
173+
|b| {
174+
b.iter(|| {
175+
let args_cloned = args.clone();
176+
black_box(unicode::lpad().invoke_with_args(ScalarFunctionArgs {
177+
args: args_cloned,
178+
arg_fields: arg_fields.clone(),
179+
number_rows: size,
180+
return_field: Field::new("f", DataType::Utf8, true).into(),
181+
config_options: Arc::clone(&config_options),
182+
}))
183+
})
184+
},
185+
);
186+
187+
// StringView type with longer strings
188+
let args = create_pad_args::<i32>(size, 20, 50, true);
189+
let arg_fields = args
190+
.iter()
191+
.enumerate()
192+
.map(|(idx, arg)| {
193+
Field::new(format!("arg_{idx}"), arg.data_type(), true).into()
194+
})
195+
.collect::<Vec<_>>();
196+
197+
group.bench_function(
198+
format!("lpad stringview [size={size}, str_len=20, target=50]"),
199+
|b| {
200+
b.iter(|| {
201+
let args_cloned = args.clone();
202+
black_box(unicode::lpad().invoke_with_args(ScalarFunctionArgs {
203+
args: args_cloned,
204+
arg_fields: arg_fields.clone(),
205+
number_rows: size,
206+
return_field: Field::new("f", DataType::Utf8View, true).into(),
207+
config_options: Arc::clone(&config_options),
208+
}))
209+
})
210+
},
211+
);
148212

149213
group.finish();
214+
}
215+
216+
for size in [1024, 4096] {
217+
let mut group = c.benchmark_group(format!("rpad size={size}"));
218+
group.sampling_mode(SamplingMode::Flat);
219+
group.sample_size(10);
220+
group.measurement_time(Duration::from_secs(10));
221+
222+
// Utf8 type
223+
let args = create_pad_args::<i32>(size, 5, 20, false);
224+
let arg_fields = args
225+
.iter()
226+
.enumerate()
227+
.map(|(idx, arg)| {
228+
Field::new(format!("arg_{idx}"), arg.data_type(), true).into()
229+
})
230+
.collect::<Vec<_>>();
231+
let config_options = Arc::new(ConfigOptions::default());
232+
233+
group.bench_function(
234+
format!("rpad utf8 [size={size}, str_len=5, target=20]"),
235+
|b| {
236+
b.iter(|| {
237+
let args_cloned = args.clone();
238+
black_box(unicode::rpad().invoke_with_args(ScalarFunctionArgs {
239+
args: args_cloned,
240+
arg_fields: arg_fields.clone(),
241+
number_rows: size,
242+
return_field: Field::new("f", DataType::Utf8, true).into(),
243+
config_options: Arc::clone(&config_options),
244+
}))
245+
})
246+
},
247+
);
248+
249+
// StringView type
250+
let args = create_pad_args::<i32>(size, 5, 20, true);
251+
let arg_fields = args
252+
.iter()
253+
.enumerate()
254+
.map(|(idx, arg)| {
255+
Field::new(format!("arg_{idx}"), arg.data_type(), true).into()
256+
})
257+
.collect::<Vec<_>>();
258+
259+
group.bench_function(
260+
format!("rpad stringview [size={size}, str_len=5, target=20]"),
261+
|b| {
262+
b.iter(|| {
263+
let args_cloned = args.clone();
264+
black_box(unicode::rpad().invoke_with_args(ScalarFunctionArgs {
265+
args: args_cloned,
266+
arg_fields: arg_fields.clone(),
267+
number_rows: size,
268+
return_field: Field::new("f", DataType::Utf8View, true).into(),
269+
config_options: Arc::clone(&config_options),
270+
}))
271+
})
272+
},
273+
);
150274

151-
let mut group = c.benchmark_group("rpad function");
275+
// Utf8 type with longer strings
276+
let args = create_pad_args::<i32>(size, 20, 50, false);
277+
let arg_fields = args
278+
.iter()
279+
.enumerate()
280+
.map(|(idx, arg)| {
281+
Field::new(format!("arg_{idx}"), arg.data_type(), true).into()
282+
})
283+
.collect::<Vec<_>>();
152284

153-
let args = create_args::<i32>(size, 32, false);
154-
group.bench_function(BenchmarkId::new("utf8 type", size), |b| {
155-
b.iter(|| black_box(invoke_pad_with_args(args.clone(), size, false).unwrap()))
156-
});
285+
group.bench_function(
286+
format!("rpad utf8 [size={size}, str_len=20, target=50]"),
287+
|b| {
288+
b.iter(|| {
289+
let args_cloned = args.clone();
290+
black_box(unicode::rpad().invoke_with_args(ScalarFunctionArgs {
291+
args: args_cloned,
292+
arg_fields: arg_fields.clone(),
293+
number_rows: size,
294+
return_field: Field::new("f", DataType::Utf8, true).into(),
295+
config_options: Arc::clone(&config_options),
296+
}))
297+
})
298+
},
299+
);
157300

158-
let args = create_args::<i64>(size, 32, false);
159-
group.bench_function(BenchmarkId::new("largeutf8 type", size), |b| {
160-
b.iter(|| black_box(invoke_pad_with_args(args.clone(), size, false).unwrap()))
161-
});
301+
// StringView type with longer strings
302+
let args = create_pad_args::<i32>(size, 20, 50, true);
303+
let arg_fields = args
304+
.iter()
305+
.enumerate()
306+
.map(|(idx, arg)| {
307+
Field::new(format!("arg_{idx}"), arg.data_type(), true).into()
308+
})
309+
.collect::<Vec<_>>();
162310

163-
// rpad for stringview type
164-
let args = create_args::<i32>(size, 32, true);
165-
group.bench_function(BenchmarkId::new("stringview type", size), |b| {
166-
b.iter(|| black_box(invoke_pad_with_args(args.clone(), size, false).unwrap()))
167-
});
311+
group.bench_function(
312+
format!("rpad stringview [size={size}, str_len=20, target=50]"),
313+
|b| {
314+
b.iter(|| {
315+
let args_cloned = args.clone();
316+
black_box(unicode::rpad().invoke_with_args(ScalarFunctionArgs {
317+
args: args_cloned,
318+
arg_fields: arg_fields.clone(),
319+
number_rows: size,
320+
return_field: Field::new("f", DataType::Utf8View, true).into(),
321+
config_options: Arc::clone(&config_options),
322+
}))
323+
})
324+
},
325+
);
168326

169327
group.finish();
170328
}

0 commit comments

Comments
 (0)