Skip to content

Commit c5e99e5

Browse files
authored
perf: Optimize scalar path for ascii function (#19951)
## 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. --> - Part of apache/datafusion-comet#2986. ## Rationale for this change The `ascii` function currently converts scalar inputs to arrays before processing via `make_scalar_function`. Adding a scalar fast path avoids this overhead and improves performance. <!-- 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? 1. Refactored `invoke_with_args` to use `match` statement for handling both scalar and array inputs 2. Added scalar fast path for `Utf8`, `LargeUtf8`, and `Utf8View` scalar inputs | Type | Before | After | Speedup | |------|--------|-------|---------| | **ascii/scalar_utf8** | 234 ns | 56 ns | **4.2x** | | **ascii/scalar_utf8view** | 206 ns | 57 ns | **3.6x** | <!-- 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? Yes <!-- 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 17cbff0 commit c5e99e5

2 files changed

Lines changed: 57 additions & 4 deletions

File tree

datafusion/functions/benches/ascii.rs

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,43 @@ mod helper;
2020

2121
use arrow::datatypes::{DataType, Field};
2222
use criterion::{Criterion, criterion_group, criterion_main};
23+
use datafusion_common::ScalarValue;
2324
use datafusion_common::config::ConfigOptions;
24-
use datafusion_expr::ScalarFunctionArgs;
25+
use datafusion_expr::{ColumnarValue, ScalarFunctionArgs};
2526
use helper::gen_string_array;
2627
use std::hint::black_box;
2728
use std::sync::Arc;
2829

2930
fn criterion_benchmark(c: &mut Criterion) {
3031
let ascii = datafusion_functions::string::ascii();
32+
let config_options = Arc::new(ConfigOptions::default());
33+
34+
// Scalar benchmarks (outside loop)
35+
c.bench_function("ascii/scalar_utf8", |b| {
36+
let args = ScalarFunctionArgs {
37+
args: vec![ColumnarValue::Scalar(ScalarValue::Utf8(Some(
38+
"hello".to_string(),
39+
)))],
40+
arg_fields: vec![Field::new("a", DataType::Utf8, false).into()],
41+
number_rows: 1,
42+
return_field: Field::new("f", DataType::Int32, true).into(),
43+
config_options: Arc::clone(&config_options),
44+
};
45+
b.iter(|| black_box(ascii.invoke_with_args(args.clone()).unwrap()))
46+
});
47+
48+
c.bench_function("ascii/scalar_utf8view", |b| {
49+
let args = ScalarFunctionArgs {
50+
args: vec![ColumnarValue::Scalar(ScalarValue::Utf8View(Some(
51+
"hello".to_string(),
52+
)))],
53+
arg_fields: vec![Field::new("a", DataType::Utf8View, false).into()],
54+
number_rows: 1,
55+
return_field: Field::new("f", DataType::Int32, true).into(),
56+
config_options: Arc::clone(&config_options),
57+
};
58+
b.iter(|| black_box(ascii.invoke_with_args(args.clone()).unwrap()))
59+
});
3160

3261
// All benches are single batch run with 8192 rows
3362
const N_ROWS: usize = 8192;

datafusion/functions/src/string/ascii.rs

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

18-
use crate::utils::make_scalar_function;
1918
use arrow::array::{ArrayRef, AsArray, Int32Array, StringArrayType};
2019
use arrow::datatypes::DataType;
2120
use arrow::error::ArrowError;
2221
use datafusion_common::types::logical_string;
23-
use datafusion_common::{Result, internal_err};
22+
use datafusion_common::utils::take_function_args;
23+
use datafusion_common::{Result, ScalarValue, internal_err};
2424
use datafusion_expr::{ColumnarValue, Documentation, TypeSignatureClass};
2525
use datafusion_expr::{ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility};
2626
use datafusion_expr_common::signature::Coercion;
@@ -91,7 +91,31 @@ impl ScalarUDFImpl for AsciiFunc {
9191
}
9292

9393
fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
94-
make_scalar_function(ascii, vec![])(&args.args)
94+
let [arg] = take_function_args(self.name(), args.args)?;
95+
96+
match arg {
97+
ColumnarValue::Scalar(scalar) => {
98+
if scalar.is_null() {
99+
return Ok(ColumnarValue::Scalar(ScalarValue::Int32(None)));
100+
}
101+
102+
match scalar {
103+
ScalarValue::Utf8(Some(s))
104+
| ScalarValue::LargeUtf8(Some(s))
105+
| ScalarValue::Utf8View(Some(s)) => {
106+
let result = s.chars().next().map_or(0, |c| c as i32);
107+
Ok(ColumnarValue::Scalar(ScalarValue::Int32(Some(result))))
108+
}
109+
_ => {
110+
internal_err!(
111+
"Unexpected data type {:?} for function ascii",
112+
scalar.data_type()
113+
)
114+
}
115+
}
116+
}
117+
ColumnarValue::Array(array) => Ok(ColumnarValue::Array(ascii(&[array])?)),
118+
}
95119
}
96120

97121
fn documentation(&self) -> Option<&Documentation> {

0 commit comments

Comments
 (0)