alamb commented on code in PR #9973:
URL: https://github.com/apache/arrow-datafusion/pull/9973#discussion_r1554566944


##########
datafusion/functions/src/unicode/substrindex.rs:
##########
@@ -112,18 +112,22 @@ pub fn substr_index<T: OffsetSizeTrait>(args: 
&[ArrayRef]) -> Result<ArrayRef> {
                     return Some(String::new());
                 }
 
-                let splitted: Box<dyn Iterator<Item = _>> = if n > 0 {
-                    Box::new(string.split(delimiter))
+                let occurrences = 
usize::try_from(n.unsigned_abs()).unwrap_or(usize::MAX);
+                let length = if n > 0 {
+                    let splitted = string.split(delimiter);
+                    splitted
+                        .take(occurrences)
+                        .map(|s| s.len() + delimiter.len())
+                        .sum::<usize>()
+                        - delimiter.len()
                 } else {
-                    Box::new(string.rsplit(delimiter))
+                    let splitted = string.rsplit(delimiter);
+                    splitted
+                        .take(occurrences)
+                        .map(|s| s.len() + delimiter.len())
+                        .sum::<usize>()
+                        - delimiter.len()
                 };
-                let occurrences = 
usize::try_from(n.unsigned_abs()).unwrap_or(usize::MAX);
-                // The length of the substring covered by substr_index.
-                let length = splitted
-                    .take(occurrences) // at least 1 element, since n != 0
-                    .map(|s| s.len() + delimiter.len())
-                    .sum::<usize>()
-                    - delimiter.len();
                 if n > 0 {
                     Some(string[..length].to_owned())

Review Comment:
   This code looks much nicer -- thank you @kevinmingtarja 
   
   Something else you could do is avoid the `String` creation here entirely -- 
creating `String`s for each row is non ideal for two reasons:
   1. It does an allocation 
   2. It needs to be copied *again* to the final output
   
   Specifically, using 
https://docs.rs/arrow/latest/arrow/array/type.StringBuilder.html you could 
build up the output directly 
   
   So something like
   
   ```rust
   let mut builder = StringBuilder::new();
   ...
       if n > 0 {
         builder.append_value(string[..length]));
       } else {
         builder.append_value(string[string.len() - length..])
       }
   ...
   ```
   
   The key is to avoid the `to_owned()` call



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to