This is an automated email from the ASF dual-hosted git repository.
github-bot pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/datafusion.git
The following commit(s) were added to refs/heads/main by this push:
new 05802e205b perf: Optimize factorial scalar path (#19949)
05802e205b is described below
commit 05802e205b05ed763aeaeaa45968fc0d2a26f187
Author: Kumar Ujjawal <[email protected]>
AuthorDate: Sat Jan 24 11:23:20 2026 +0530
perf: Optimize factorial scalar path (#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 #123` indicates that this PR will close issue #123.
-->
- Part of https://github.com/apache/datafusion-comet/issues/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.
-->
---
datafusion/functions/src/math/factorial.rs | 94 ++++++++++++++----------------
1 file changed, 43 insertions(+), 51 deletions(-)
diff --git a/datafusion/functions/src/math/factorial.rs
b/datafusion/functions/src/math/factorial.rs
index ffe12466dc..c1dd802140 100644
--- a/datafusion/functions/src/math/factorial.rs
+++ b/datafusion/functions/src/math/factorial.rs
@@ -22,8 +22,9 @@ use std::sync::Arc;
use arrow::datatypes::DataType::Int64;
use arrow::datatypes::{DataType, Int64Type};
-use crate::utils::make_scalar_function;
-use datafusion_common::{Result, exec_err};
+use datafusion_common::{
+ Result, ScalarValue, exec_err, internal_err, utils::take_function_args,
+};
use datafusion_expr::{
ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
Volatility,
@@ -81,7 +82,39 @@ impl ScalarUDFImpl for FactorialFunc {
}
fn invoke_with_args(&self, args: ScalarFunctionArgs) ->
Result<ColumnarValue> {
- make_scalar_function(factorial, vec![])(&args.args)
+ let [arg] = take_function_args(self.name(), args.args)?;
+
+ match arg {
+ ColumnarValue::Scalar(scalar) => {
+ if scalar.is_null() {
+ return Ok(ColumnarValue::Scalar(ScalarValue::Int64(None)));
+ }
+
+ match scalar {
+ ScalarValue::Int64(Some(v)) => {
+ let result = compute_factorial(v)?;
+
Ok(ColumnarValue::Scalar(ScalarValue::Int64(Some(result))))
+ }
+ _ => {
+ internal_err!(
+ "Unexpected data type {:?} for function factorial",
+ scalar.data_type()
+ )
+ }
+ }
+ }
+ ColumnarValue::Array(array) => match array.data_type() {
+ Int64 => {
+ let result: Int64Array = array
+ .as_primitive::<Int64Type>()
+ .try_unary(compute_factorial)?;
+ Ok(ColumnarValue::Array(Arc::new(result) as ArrayRef))
+ }
+ other => {
+ internal_err!("Unexpected data type {other:?} for function
factorial")
+ }
+ },
+ }
}
fn documentation(&self) -> Option<&Documentation> {
@@ -113,53 +146,12 @@ const FACTORIALS: [i64; 21] = [
2432902008176640000,
]; // if return type changes, this constant needs to be updated accordingly
-/// Factorial SQL function
-fn factorial(args: &[ArrayRef]) -> Result<ArrayRef> {
- match args[0].data_type() {
- Int64 => {
- let result: Int64Array =
- args[0].as_primitive::<Int64Type>().try_unary(|a| {
- if a < 0 {
- Ok(1)
- } else if a < FACTORIALS.len() as i64 {
- Ok(FACTORIALS[a as usize])
- } else {
- exec_err!("Overflow happened on FACTORIAL({a})")
- }
- })?;
- Ok(Arc::new(result) as ArrayRef)
- }
- other => exec_err!("Unsupported data type {other:?} for function
factorial."),
- }
-}
-
-#[cfg(test)]
-mod test {
- use super::*;
- use datafusion_common::cast::as_int64_array;
-
- #[test]
- fn test_factorial_i64() {
- let args: Vec<ArrayRef> = vec![
- Arc::new(Int64Array::from(vec![0, 1, 2, 4, 20, -1])), // input
- ];
-
- let result = factorial(&args).expect("failed to initialize function
factorial");
- let ints =
- as_int64_array(&result).expect("failed to initialize function
factorial");
-
- let expected = Int64Array::from(vec![1, 1, 2, 24, 2432902008176640000,
1]);
-
- assert_eq!(ints, &expected);
- }
-
- #[test]
- fn test_overflow() {
- let args: Vec<ArrayRef> = vec![
- Arc::new(Int64Array::from(vec![21])), // input
- ];
-
- let result = factorial(&args);
- assert!(result.is_err());
+fn compute_factorial(n: i64) -> Result<i64> {
+ if n < 0 {
+ Ok(1)
+ } else if n < FACTORIALS.len() as i64 {
+ Ok(FACTORIALS[n as usize])
+ } else {
+ exec_err!("Overflow happened on FACTORIAL({n})")
}
}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]