Skip to content

Commit 05802e2

Browse files
authored
perf: Optimize factorial scalar path (apache#19949)
## 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 apache#123` indicates that this PR will close issue apache#123. --> - Part of apache/datafusion-comet#2986. ## Rationale for this change The `factorial` function currently converts scalar inputs to arrays before processing. 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. Inlined array processing logic, removing `make_scalar_function` usage. | Type | Before | After | Speedup | |------|--------|-------|---------| | **factorial_scalar** | 244 ns | 102 ns | **2.4x** | <!-- 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, covered by existing SLT tests: - `scalar.slt` lines 461-477 - `math.slt` line 797 <!-- 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 1897924 commit 05802e2

File tree

1 file changed

+43
-51
lines changed

1 file changed

+43
-51
lines changed

datafusion/functions/src/math/factorial.rs

Lines changed: 43 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,9 @@ use std::sync::Arc;
2222
use arrow::datatypes::DataType::Int64;
2323
use arrow::datatypes::{DataType, Int64Type};
2424

25-
use crate::utils::make_scalar_function;
26-
use datafusion_common::{Result, exec_err};
25+
use datafusion_common::{
26+
Result, ScalarValue, exec_err, internal_err, utils::take_function_args,
27+
};
2728
use datafusion_expr::{
2829
ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
2930
Volatility,
@@ -81,7 +82,39 @@ impl ScalarUDFImpl for FactorialFunc {
8182
}
8283

8384
fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
84-
make_scalar_function(factorial, vec![])(&args.args)
85+
let [arg] = take_function_args(self.name(), args.args)?;
86+
87+
match arg {
88+
ColumnarValue::Scalar(scalar) => {
89+
if scalar.is_null() {
90+
return Ok(ColumnarValue::Scalar(ScalarValue::Int64(None)));
91+
}
92+
93+
match scalar {
94+
ScalarValue::Int64(Some(v)) => {
95+
let result = compute_factorial(v)?;
96+
Ok(ColumnarValue::Scalar(ScalarValue::Int64(Some(result))))
97+
}
98+
_ => {
99+
internal_err!(
100+
"Unexpected data type {:?} for function factorial",
101+
scalar.data_type()
102+
)
103+
}
104+
}
105+
}
106+
ColumnarValue::Array(array) => match array.data_type() {
107+
Int64 => {
108+
let result: Int64Array = array
109+
.as_primitive::<Int64Type>()
110+
.try_unary(compute_factorial)?;
111+
Ok(ColumnarValue::Array(Arc::new(result) as ArrayRef))
112+
}
113+
other => {
114+
internal_err!("Unexpected data type {other:?} for function factorial")
115+
}
116+
},
117+
}
85118
}
86119

87120
fn documentation(&self) -> Option<&Documentation> {
@@ -113,53 +146,12 @@ const FACTORIALS: [i64; 21] = [
113146
2432902008176640000,
114147
]; // if return type changes, this constant needs to be updated accordingly
115148

116-
/// Factorial SQL function
117-
fn factorial(args: &[ArrayRef]) -> Result<ArrayRef> {
118-
match args[0].data_type() {
119-
Int64 => {
120-
let result: Int64Array =
121-
args[0].as_primitive::<Int64Type>().try_unary(|a| {
122-
if a < 0 {
123-
Ok(1)
124-
} else if a < FACTORIALS.len() as i64 {
125-
Ok(FACTORIALS[a as usize])
126-
} else {
127-
exec_err!("Overflow happened on FACTORIAL({a})")
128-
}
129-
})?;
130-
Ok(Arc::new(result) as ArrayRef)
131-
}
132-
other => exec_err!("Unsupported data type {other:?} for function factorial."),
133-
}
134-
}
135-
136-
#[cfg(test)]
137-
mod test {
138-
use super::*;
139-
use datafusion_common::cast::as_int64_array;
140-
141-
#[test]
142-
fn test_factorial_i64() {
143-
let args: Vec<ArrayRef> = vec![
144-
Arc::new(Int64Array::from(vec![0, 1, 2, 4, 20, -1])), // input
145-
];
146-
147-
let result = factorial(&args).expect("failed to initialize function factorial");
148-
let ints =
149-
as_int64_array(&result).expect("failed to initialize function factorial");
150-
151-
let expected = Int64Array::from(vec![1, 1, 2, 24, 2432902008176640000, 1]);
152-
153-
assert_eq!(ints, &expected);
154-
}
155-
156-
#[test]
157-
fn test_overflow() {
158-
let args: Vec<ArrayRef> = vec![
159-
Arc::new(Int64Array::from(vec![21])), // input
160-
];
161-
162-
let result = factorial(&args);
163-
assert!(result.is_err());
149+
fn compute_factorial(n: i64) -> Result<i64> {
150+
if n < 0 {
151+
Ok(1)
152+
} else if n < FACTORIALS.len() as i64 {
153+
Ok(FACTORIALS[n as usize])
154+
} else {
155+
exec_err!("Overflow happened on FACTORIAL({n})")
164156
}
165157
}

0 commit comments

Comments
 (0)