You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "andygrove (via GitHub)" <gi...@apache.org> on 2025/12/29 17:41:45 UTC

[PR] perf: Improve performance of ltrim, rtrim, btrim [datafusion]

andygrove opened a new pull request, #19551:
URL: https://github.com/apache/datafusion/pull/19551

   ## 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 https://github.com/apache/datafusion/issues/12576
   
   ## 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.  
   -->
   
   Improve performance.
   
   ## 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.
   -->
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] perf: Improve performance of ltrim, rtrim, btrim [datafusion]

Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove commented on code in PR #19551:
URL: https://github.com/apache/datafusion/pull/19551#discussion_r2658354650


##########
datafusion/functions/src/string/common.rs:
##########
@@ -49,90 +49,69 @@ impl Display for TrimType {
     }
 }
 
+/// Perform trim operation on input string with given pattern characters.
+///
+/// Returns (trimmed_str, start_offset) where start_offset is the byte offset
+/// from the beginning of the input string where the trimmed result starts.
+#[inline]
+fn perform_trim<'a>(
+    input: &'a str,
+    pattern: &[char],
+    trim_type: TrimType,
+) -> (&'a str, u32) {
+    match trim_type {
+        TrimType::Left => {

Review Comment:
   Results are a little mixed, but mostly better. Also, the code is a little cleaner with the trait approach, IMO.
   
   | Benchmark                     | Before  | After   | Change |
   |-------------------------------|---------|---------|--------|
   | ltrim string_view short       | 50.7 µs | 47.3 µs | −6.6%  |
   | ltrim large_string short      | 44.7 µs | 42.9 µs | −4.1%  |
   | rtrim string short            | 46.0 µs | 45.0 µs | −2.3%  |
   | rtrim large_string long short | 44.8 µs | 42.8 µs | −4.5%  |
   | btrim string_view short       | 78.1 µs | 78.1 µs | ~0%    |
   | long trim scenarios           | ~280 µs | ~286 µs | +2-3%  |
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] perf: Improve performance of ltrim, rtrim, btrim [datafusion]

Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove commented on PR #19551:
URL: https://github.com/apache/datafusion/pull/19551#issuecomment-3698192513

   > These are great optimization opportunities. I’m curious how you arrived at them.
   
   We have been running microbenchmarks in the Comet subproject, comparing Spark vs Spark + Comet (queries accelerated with DataFusion), and have identified some expressions where Comet performance is worse than Spark. See https://github.com/apache/datafusion-comet/issues/2986.
   
   For the optimizations themselves, it has been a mix of manual effort and the use of Claude code.
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] perf: Improve performance of ltrim, rtrim, btrim [datafusion]

Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
Jefffrey commented on code in PR #19551:
URL: https://github.com/apache/datafusion/pull/19551#discussion_r2656731135


##########
datafusion/functions/src/string/common.rs:
##########
@@ -49,90 +49,69 @@ impl Display for TrimType {
     }
 }
 
+/// Perform trim operation on input string with given pattern characters.
+///
+/// Returns (trimmed_str, start_offset) where start_offset is the byte offset
+/// from the beginning of the input string where the trimmed result starts.
+#[inline]
+fn perform_trim<'a>(
+    input: &'a str,
+    pattern: &[char],
+    trim_type: TrimType,
+) -> (&'a str, u32) {
+    match trim_type {
+        TrimType::Left => {

Review Comment:
   I wonder if we can get speed gains by pulling this enum into a generic/trait to avoid this matching inside the loop?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] perf: Improve performance of ltrim, rtrim, btrim [datafusion]

Posted by "2010YOUY01 (via GitHub)" <gi...@apache.org>.
2010YOUY01 commented on PR #19551:
URL: https://github.com/apache/datafusion/pull/19551#issuecomment-3698124701

   These are great optimization opportunities. I’m curious how you arrived at them.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] perf: Improve performance of ltrim, rtrim, btrim [datafusion]

Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove commented on PR #19551:
URL: https://github.com/apache/datafusion/pull/19551#issuecomment-3704219626

   I ran benchmarks again and found a smaller speedup. I need to investigate:
   
   | Test Case                                | Main      | PR #19551 | Change        |
   |------------------------------------------|-----------|-----------|---------------|
   | string_view [size=1024, len<=12]         | 19.57 µs  | 19.24 µs  | -1.62% faster |
   | string_view [size=1024, len>12, out>12]  | 19.69 µs  | 19.53 µs  | -0.77% faster |
   | string_view [size=1024, len>12, out<=12] | 69.51 µs  | 69.29 µs  | -0.32% faster |
   | string_view [size=4096, len<=12]         | 77.64 µs  | 76.41 µs  | -1.55% faster |
   | string_view [size=4096, len>12, out>12]  | 76.43 µs  | 76.20 µs  | -0.28% faster |
   | string_view [size=4096, len>12, out<=12] | 277.37 µs | 274.55 µs | -1.01% faster |
   | string_view [size=8192, len<=12]         | 150.74 µs | 151.48 µs | +0.49% slower |
   | string_view [size=8192, len>12, out>12]  | 153.22 µs | 151.76 µs | -0.95% faster |
   | string_view [size=8192, len>12, out<=12] | 551.41 µs | 550.43 µs | -0.18% faster |
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] perf: Improve performance of ltrim, rtrim, btrim [datafusion]

Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove commented on code in PR #19551:
URL: https://github.com/apache/datafusion/pull/19551#discussion_r2658323654


##########
datafusion/functions/src/string/common.rs:
##########
@@ -49,90 +49,69 @@ impl Display for TrimType {
     }
 }
 
+/// Perform trim operation on input string with given pattern characters.
+///
+/// Returns (trimmed_str, start_offset) where start_offset is the byte offset
+/// from the beginning of the input string where the trimmed result starts.
+#[inline]
+fn perform_trim<'a>(
+    input: &'a str,
+    pattern: &[char],
+    trim_type: TrimType,
+) -> (&'a str, u32) {
+    match trim_type {
+        TrimType::Left => {

Review Comment:
   Good idea. I am investigating this now.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] perf: Improve performance of ltrim, rtrim, btrim [datafusion]

Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
Jefffrey commented on PR #19551:
URL: https://github.com/apache/datafusion/pull/19551#issuecomment-3706598528

   Thanks @andygrove & @comphead 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] perf: Improve performance of ltrim, rtrim, btrim [datafusion]

Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on code in PR #19551:
URL: https://github.com/apache/datafusion/pull/19551#discussion_r2651610456


##########
datafusion/functions/benches/trim.rs:
##########
@@ -48,28 +48,58 @@ impl fmt::Display for StringArrayType {
     }
 }
 
-/// returns an array of strings, and `characters` as a ScalarValue
-pub fn create_string_array_and_characters(
+#[derive(Clone, Copy)]
+pub enum TrimType {
+    Ltrim,
+    Rtrim,
+    Btrim,
+}
+
+impl fmt::Display for TrimType {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        match self {
+            TrimType::Ltrim => f.write_str("ltrim"),
+            TrimType::Rtrim => f.write_str("rtrim"),
+            TrimType::Btrim => f.write_str("btrim"),
+        }
+    }
+}
+
+/// Returns an array of strings with trim characters positioned according to trim type,
+/// and `characters` as a ScalarValue.
+///
+/// For ltrim: trim characters are at the start (prefix)
+/// For rtrim: trim characters are at the end (suffix)
+/// For btrim: trim characters are at both start and end
+fn create_string_array_and_characters(
     size: usize,
     characters: &str,
     trimmed: &str,
     remaining_len: usize,
     string_array_type: StringArrayType,
+    trim_type: TrimType,
 ) -> (ArrayRef, ScalarValue) {
     let rng = &mut StdRng::seed_from_u64(42);
 
     // Create `size` rows:
     //   - 10% rows will be `None`
-    //   - Other 90% will be strings with same `remaining_len` lengths
-    // We will build the string array on it later.
+    //   - Other 90% will be strings with `remaining_len` content length
     let string_iter = (0..size).map(|_| {
         if rng.random::<f32>() < 0.1 {
             None
         } else {
-            let mut value = trimmed.as_bytes().to_vec();
-            let generated = rng.sample_iter(&Alphanumeric).take(remaining_len);
-            value.extend(generated);
-            Some(String::from_utf8(value).unwrap())
+            let content: String = rng
+                .sample_iter(&Alphanumeric)
+                .take(remaining_len)
+                .map(char::from)
+                .collect();
+
+            let value = match trim_type {
+                TrimType::Ltrim => format!("{trimmed}{content}"),
+                TrimType::Rtrim => format!("{content}{trimmed}"),
+                TrimType::Btrim => format!("{trimmed}{content}{trimmed}"),
+            };

Review Comment:
   ```suggestion
   let value = {
       let (prefix, suffix) = match trim_type {
           TrimType::Ltrim => (trimmed, ""),
           TrimType::Rtrim => ("", trimmed),
           TrimType::Btrim => (trimmed, trimmed),
       };
   
       let mut s = String::with_capacity(
           prefix.len() + content.len() + suffix.len()
       );
   
       s.push_str(prefix);
       s.push_str(content);
       s.push_str(suffix);
       s
   };
   ```
   
   Slightly more verbose but less string allocations on concats



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] perf: Improve performance of ltrim, rtrim, btrim [datafusion]

Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove commented on code in PR #19551:
URL: https://github.com/apache/datafusion/pull/19551#discussion_r2656580452


##########
datafusion/functions/benches/trim.rs:
##########
@@ -48,28 +48,58 @@ impl fmt::Display for StringArrayType {
     }
 }
 
-/// returns an array of strings, and `characters` as a ScalarValue
-pub fn create_string_array_and_characters(
+#[derive(Clone, Copy)]
+pub enum TrimType {
+    Ltrim,
+    Rtrim,
+    Btrim,
+}
+
+impl fmt::Display for TrimType {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        match self {
+            TrimType::Ltrim => f.write_str("ltrim"),
+            TrimType::Rtrim => f.write_str("rtrim"),
+            TrimType::Btrim => f.write_str("btrim"),
+        }
+    }
+}
+
+/// Returns an array of strings with trim characters positioned according to trim type,
+/// and `characters` as a ScalarValue.
+///
+/// For ltrim: trim characters are at the start (prefix)
+/// For rtrim: trim characters are at the end (suffix)
+/// For btrim: trim characters are at both start and end
+fn create_string_array_and_characters(
     size: usize,
     characters: &str,
     trimmed: &str,
     remaining_len: usize,
     string_array_type: StringArrayType,
+    trim_type: TrimType,
 ) -> (ArrayRef, ScalarValue) {
     let rng = &mut StdRng::seed_from_u64(42);
 
     // Create `size` rows:
     //   - 10% rows will be `None`
-    //   - Other 90% will be strings with same `remaining_len` lengths
-    // We will build the string array on it later.
+    //   - Other 90% will be strings with `remaining_len` content length
     let string_iter = (0..size).map(|_| {
         if rng.random::<f32>() < 0.1 {
             None
         } else {
-            let mut value = trimmed.as_bytes().to_vec();
-            let generated = rng.sample_iter(&Alphanumeric).take(remaining_len);
-            value.extend(generated);
-            Some(String::from_utf8(value).unwrap())
+            let content: String = rng
+                .sample_iter(&Alphanumeric)
+                .take(remaining_len)
+                .map(char::from)
+                .collect();
+
+            let value = match trim_type {
+                TrimType::Ltrim => format!("{trimmed}{content}"),
+                TrimType::Rtrim => format!("{content}{trimmed}"),
+                TrimType::Btrim => format!("{trimmed}{content}{trimmed}"),
+            };

Review Comment:
   This code is creating the test data to be used in the benchmark. I don't think we need to optimize this too much?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] perf: Improve performance of ltrim, rtrim, btrim [datafusion]

Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
Jefffrey merged PR #19551:
URL: https://github.com/apache/datafusion/pull/19551


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org