Skip to content

Commit afc9121

Browse files
authored
Optimize concat/concat_ws scalar path by pre-allocating memory (#19547)
## 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. --> This PR improves performance by: - ~~Using exact `Utf8View` byte size (sum of data buffers) instead of row-based approximation.~~ - Building results via `.concat()`/`.join(sep)` on a pre-allocated `Vec<&str>` to avoid `String` reallocations. ### Benchmark | Case | Before | After | Change | | :--- | :--------: | :--------: | ---: | | concat_ws_scalar/8 | 299.18 ns | 233.18 ns | -21.93% | | concat_ws_scalar/32 | 327.53 ns | 251.44 ns | -23.23% | | concat_ws_scalar/128 | 405.80 ns | 271.27 ns | -33.15% | | concat_ws_scalar/4096 | 976.02 ns | 791.33 ns | -18.92% | | concat_scalar/8 | 248.71 ns | 221.24 ns | -11.05% | | concat_scalar/32 | 284.26 ns | 240.53 ns | -15.39% | | concat_scalar/128 | 301.91 ns | 257.61 ns | -14.67% | | concat_scalar/4096 | 916.68 ns | 805.33 ns | -12.15% | ## 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. --> Performance optimization for `concat` and `concat_ws` functions scalar path. ## Are these changes tested? - Existing unit and integration 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. It's a pure performance optimization. <!-- 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 3087ca8 commit afc9121

5 files changed

Lines changed: 234 additions & 32 deletions

File tree

datafusion/functions/Cargo.toml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,11 @@ harness = false
107107
name = "concat"
108108
required-features = ["string_expressions"]
109109

110+
[[bench]]
111+
harness = false
112+
name = "concat_ws"
113+
required-features = ["string_expressions"]
114+
110115
[[bench]]
111116
harness = false
112117
name = "to_timestamp"

datafusion/functions/benches/concat.rs

Lines changed: 97 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,16 +17,18 @@
1717

1818
use arrow::array::ArrayRef;
1919
use arrow::datatypes::{DataType, Field};
20-
use arrow::util::bench_util::create_string_array_with_len;
20+
use arrow::util::bench_util::{create_string_array_with_len, create_string_view_array};
2121
use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main};
2222
use datafusion_common::ScalarValue;
2323
use datafusion_common::config::ConfigOptions;
2424
use datafusion_expr::{ColumnarValue, ScalarFunctionArgs};
2525
use datafusion_functions::string::concat;
26+
use rand::Rng;
27+
use rand::distr::Alphanumeric;
2628
use std::hint::black_box;
2729
use std::sync::Arc;
2830

29-
fn create_args(size: usize, str_len: usize) -> Vec<ColumnarValue> {
31+
fn create_array_args(size: usize, str_len: usize) -> Vec<ColumnarValue> {
3032
let array = Arc::new(create_string_array_with_len::<i32>(size, 0.2, str_len));
3133
let scalar = ScalarValue::Utf8(Some(", ".to_string()));
3234
vec![
@@ -36,9 +38,37 @@ fn create_args(size: usize, str_len: usize) -> Vec<ColumnarValue> {
3638
]
3739
}
3840

41+
fn create_array_args_view(size: usize) -> Vec<ColumnarValue> {
42+
let array = Arc::new(create_string_view_array(size, 0.2));
43+
let scalar = ScalarValue::Utf8(Some(", ".to_string()));
44+
vec![
45+
ColumnarValue::Array(Arc::clone(&array) as ArrayRef),
46+
ColumnarValue::Scalar(scalar),
47+
ColumnarValue::Array(array),
48+
]
49+
}
50+
51+
fn generate_random_string(str_len: usize) -> String {
52+
rand::rng()
53+
.sample_iter(&Alphanumeric)
54+
.take(str_len)
55+
.map(char::from)
56+
.collect()
57+
}
58+
59+
fn create_scalar_args(count: usize, str_len: usize) -> Vec<ColumnarValue> {
60+
std::iter::repeat_with(|| {
61+
let s = generate_random_string(str_len);
62+
ColumnarValue::Scalar(ScalarValue::Utf8(Some(s)))
63+
})
64+
.take(count)
65+
.collect()
66+
}
67+
3968
fn criterion_benchmark(c: &mut Criterion) {
69+
// Benchmark for array concat
4070
for size in [1024, 4096, 8192] {
41-
let args = create_args(size, 32);
71+
let args = create_array_args(size, 32);
4272
let arg_fields = args
4373
.iter()
4474
.enumerate()
@@ -67,6 +97,70 @@ fn criterion_benchmark(c: &mut Criterion) {
6797
});
6898
group.finish();
6999
}
100+
101+
// Benchmark for StringViewArray concat
102+
for size in [1024, 4096, 8192] {
103+
let args = create_array_args_view(size);
104+
let arg_fields = args
105+
.iter()
106+
.enumerate()
107+
.map(|(idx, arg)| {
108+
// Use Utf8View for array args
109+
let dt = if matches!(arg, ColumnarValue::Array(_)) {
110+
DataType::Utf8View
111+
} else {
112+
DataType::Utf8 // scalar remains Utf8
113+
};
114+
Field::new(format!("arg_{idx}"), dt, true).into()
115+
})
116+
.collect::<Vec<_>>();
117+
let config_options = Arc::new(ConfigOptions::default());
118+
119+
let mut group = c.benchmark_group("concat function");
120+
group.bench_function(BenchmarkId::new("concat_view", size), |b| {
121+
b.iter(|| {
122+
let args_cloned = args.clone();
123+
black_box(
124+
concat()
125+
.invoke_with_args(ScalarFunctionArgs {
126+
args: args_cloned,
127+
arg_fields: arg_fields.clone(),
128+
number_rows: size,
129+
return_field: Field::new("f", DataType::Utf8View, true)
130+
.into(),
131+
config_options: Arc::clone(&config_options),
132+
})
133+
.unwrap(),
134+
)
135+
})
136+
});
137+
group.finish();
138+
}
139+
140+
// Benchmark for scalar concat
141+
let scalar_args = create_scalar_args(10, 100);
142+
let scalar_arg_fields = scalar_args
143+
.iter()
144+
.enumerate()
145+
.map(|(idx, arg)| Field::new(format!("arg_{idx}"), arg.data_type(), true).into())
146+
.collect::<Vec<_>>();
147+
let mut group = c.benchmark_group("concat function");
148+
group.bench_function(BenchmarkId::new("concat", "scalar"), |b| {
149+
b.iter(|| {
150+
let args_cloned = scalar_args.clone();
151+
black_box(
152+
concat()
153+
.invoke_with_args(ScalarFunctionArgs {
154+
args: args_cloned,
155+
arg_fields: scalar_arg_fields.clone(),
156+
number_rows: 1,
157+
return_field: Field::new("f", DataType::Utf8, true).into(),
158+
config_options: Arc::new(ConfigOptions::default()),
159+
})
160+
.unwrap(),
161+
)
162+
})
163+
});
70164
}
71165

72166
criterion_group!(benches, criterion_benchmark);
Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
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+
use arrow::array::ArrayRef;
19+
use arrow::datatypes::{DataType, Field};
20+
use arrow::util::bench_util::create_string_array_with_len;
21+
use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main};
22+
use datafusion_common::ScalarValue;
23+
use datafusion_common::config::ConfigOptions;
24+
use datafusion_expr::{ColumnarValue, ScalarFunctionArgs};
25+
use datafusion_functions::string::concat_ws;
26+
use rand::Rng;
27+
use rand::distr::Alphanumeric;
28+
use std::hint::black_box;
29+
use std::sync::Arc;
30+
31+
fn create_array_args(size: usize, str_len: usize) -> Vec<ColumnarValue> {
32+
let array = Arc::new(create_string_array_with_len::<i32>(size, 0.2, str_len));
33+
let scalar = ScalarValue::Utf8(Some(", ".to_string()));
34+
vec![
35+
ColumnarValue::Scalar(scalar),
36+
ColumnarValue::Array(Arc::clone(&array) as ArrayRef),
37+
ColumnarValue::Array(array),
38+
]
39+
}
40+
41+
fn generate_random_string(str_len: usize) -> String {
42+
rand::rng()
43+
.sample_iter(&Alphanumeric)
44+
.take(str_len)
45+
.map(char::from)
46+
.collect()
47+
}
48+
49+
fn create_scalar_args(count: usize, str_len: usize) -> Vec<ColumnarValue> {
50+
let mut args = Vec::with_capacity(count + 1);
51+
52+
args.push(ColumnarValue::Scalar(ScalarValue::Utf8(Some(
53+
",".to_string(),
54+
))));
55+
56+
for _ in 0..count {
57+
let s = generate_random_string(str_len);
58+
args.push(ColumnarValue::Scalar(ScalarValue::Utf8(Some(s))));
59+
}
60+
args
61+
}
62+
63+
fn criterion_benchmark(c: &mut Criterion) {
64+
// Benchmark for array concat_ws
65+
for size in [1024, 4096, 8192] {
66+
let args = create_array_args(size, 32);
67+
let arg_fields = args
68+
.iter()
69+
.enumerate()
70+
.map(|(idx, arg)| {
71+
Field::new(format!("arg_{idx}"), arg.data_type(), true).into()
72+
})
73+
.collect::<Vec<_>>();
74+
let config_options = Arc::new(ConfigOptions::default());
75+
76+
let mut group = c.benchmark_group("concat_ws function");
77+
group.bench_function(BenchmarkId::new("concat_ws", size), |b| {
78+
b.iter(|| {
79+
let args_cloned = args.clone();
80+
black_box(
81+
concat_ws()
82+
.invoke_with_args(ScalarFunctionArgs {
83+
args: args_cloned,
84+
arg_fields: arg_fields.clone(),
85+
number_rows: size,
86+
return_field: Field::new("f", DataType::Utf8, true).into(),
87+
config_options: Arc::clone(&config_options),
88+
})
89+
.unwrap(),
90+
)
91+
})
92+
});
93+
group.finish();
94+
}
95+
96+
// Benchmark for scalar concat_ws
97+
let scalar_args = create_scalar_args(10, 100);
98+
let scalar_arg_fields = scalar_args
99+
.iter()
100+
.enumerate()
101+
.map(|(idx, arg)| Field::new(format!("arg_{idx}"), arg.data_type(), true).into())
102+
.collect::<Vec<_>>();
103+
let mut group = c.benchmark_group("concat_ws function");
104+
group.bench_function(BenchmarkId::new("concat_ws", "scalar"), |b| {
105+
b.iter(|| {
106+
let args_cloned = scalar_args.clone();
107+
black_box(
108+
concat_ws()
109+
.invoke_with_args(ScalarFunctionArgs {
110+
args: args_cloned,
111+
arg_fields: scalar_arg_fields.clone(),
112+
number_rows: 1,
113+
return_field: Field::new("f", DataType::Utf8, true).into(),
114+
config_options: Arc::new(ConfigOptions::default()),
115+
})
116+
.unwrap(),
117+
)
118+
})
119+
});
120+
}
121+
122+
criterion_group!(benches, criterion_benchmark);
123+
criterion_main!(benches);

datafusion/functions/src/string/concat.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -130,21 +130,22 @@ impl ScalarUDFImpl for ConcatFunc {
130130

131131
// Scalar
132132
if array_len.is_none() {
133-
let mut result = String::new();
134-
for arg in args {
133+
let mut values = Vec::with_capacity(args.len());
134+
for arg in &args {
135135
let ColumnarValue::Scalar(scalar) = arg else {
136136
return internal_err!("concat expected scalar value, got {arg:?}");
137137
};
138138

139139
match scalar.try_as_str() {
140-
Some(Some(v)) => result.push_str(v),
140+
Some(Some(v)) => values.push(v),
141141
Some(None) => {} // null literal
142142
None => plan_err!(
143143
"Concat function does not support scalar type {}",
144144
scalar
145145
)?,
146146
}
147147
}
148+
let result = values.concat();
148149

149150
return match return_datatype {
150151
DataType::Utf8View => {

datafusion/functions/src/string/concat_ws.rs

Lines changed: 5 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -136,43 +136,22 @@ impl ScalarUDFImpl for ConcatWsFunc {
136136
None => return internal_err!("Expected string literal, got {scalar:?}"),
137137
};
138138

139-
let mut result = String::new();
140-
// iterator over Option<str>
141-
let iter = &mut args[1..].iter().map(|arg| {
139+
let mut values = Vec::with_capacity(args.len() - 1);
140+
for arg in &args[1..] {
142141
let ColumnarValue::Scalar(scalar) = arg else {
143142
// loop above checks for all args being scalar
144143
unreachable!()
145144
};
146-
scalar.try_as_str()
147-
});
148-
149-
// append first non null arg
150-
for scalar in iter.by_ref() {
151-
match scalar {
152-
Some(Some(s)) => {
153-
result.push_str(s);
154-
break;
155-
}
156-
Some(None) => {} // null literal string
157-
None => {
158-
return internal_err!("Expected string literal, got {scalar:?}");
159-
}
160-
}
161-
}
162145

163-
// handle subsequent non null args
164-
for scalar in iter.by_ref() {
165-
match scalar {
166-
Some(Some(s)) => {
167-
result.push_str(sep);
168-
result.push_str(s);
169-
}
146+
match scalar.try_as_str() {
147+
Some(Some(v)) => values.push(v),
170148
Some(None) => {} // null literal string
171149
None => {
172150
return internal_err!("Expected string literal, got {scalar:?}");
173151
}
174152
}
175153
}
154+
let result = values.join(sep);
176155

177156
return Ok(ColumnarValue::Scalar(ScalarValue::Utf8(Some(result))));
178157
}

0 commit comments

Comments
 (0)