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


##########
datafusion/physical-expr/src/string_expressions.rs:
##########
@@ -227,6 +229,132 @@ pub fn concat(args: &[ColumnarValue]) -> 
Result<ColumnarValue> {
     }
 }
 
+enum ColumnarValueRef<'a> {
+    Scalar(&'a [u8]),
+    Array(&'a StringArray),
+}
+
+impl<'a> ColumnarValueRef<'a> {
+    #[inline]
+    fn is_valid(&self, i: usize) -> bool {
+        match &self {
+            Self::Scalar(_) => true,
+            Self::Array(array) => array.is_valid(i),
+        }
+    }
+
+    #[inline]
+    fn nulls(&self) -> Option<NullBuffer> {
+        match &self {
+            Self::Scalar(_) => None,
+            Self::Array(array) => array.nulls().map(|b| b.clone()),
+        }
+    }
+}
+
+struct StringArrayBuilder {
+    offsets_buffer: MutableBuffer,
+    value_buffer: MutableBuffer,
+}
+
+impl StringArrayBuilder {
+    fn with_capacity(item_capacity: usize, data_capacity: usize) -> Self {
+        let mut offsets_buffer = MutableBuffer::with_capacity(
+            (item_capacity + 1) * std::mem::size_of::<i32>(),
+        );
+        unsafe { offsets_buffer.push_unchecked(0_i32) };
+        Self {
+            offsets_buffer,
+            value_buffer: MutableBuffer::with_capacity(data_capacity),
+        }
+    }
+
+    fn write<const CHECK_VALID: bool>(&mut self, column: &ColumnarValueRef, i: 
usize) {
+        match column {
+            ColumnarValueRef::Scalar(s) => {
+                self.value_buffer.extend_from_slice(s);

Review Comment:
   Is the primary speed savings gained from not checking UTF8 validity (and 
just copying byte slices)?



##########
datafusion/physical-expr/src/string_expressions.rs:
##########
@@ -227,6 +229,132 @@ pub fn concat(args: &[ColumnarValue]) -> 
Result<ColumnarValue> {
     }
 }
 
+enum ColumnarValueRef<'a> {
+    Scalar(&'a [u8]),
+    Array(&'a StringArray),
+}
+
+impl<'a> ColumnarValueRef<'a> {
+    #[inline]
+    fn is_valid(&self, i: usize) -> bool {
+        match &self {
+            Self::Scalar(_) => true,
+            Self::Array(array) => array.is_valid(i),
+        }
+    }
+
+    #[inline]
+    fn nulls(&self) -> Option<NullBuffer> {
+        match &self {
+            Self::Scalar(_) => None,
+            Self::Array(array) => array.nulls().map(|b| b.clone()),
+        }
+    }
+}
+
+struct StringArrayBuilder {
+    offsets_buffer: MutableBuffer,
+    value_buffer: MutableBuffer,
+}
+
+impl StringArrayBuilder {
+    fn with_capacity(item_capacity: usize, data_capacity: usize) -> Self {
+        let mut offsets_buffer = MutableBuffer::with_capacity(
+            (item_capacity + 1) * std::mem::size_of::<i32>(),
+        );
+        unsafe { offsets_buffer.push_unchecked(0_i32) };
+        Self {
+            offsets_buffer,
+            value_buffer: MutableBuffer::with_capacity(data_capacity),
+        }
+    }
+
+    fn write<const CHECK_VALID: bool>(&mut self, column: &ColumnarValueRef, i: 
usize) {
+        match column {
+            ColumnarValueRef::Scalar(s) => {
+                self.value_buffer.extend_from_slice(s);
+            }
+            ColumnarValueRef::Array(array) => {
+                if !CHECK_VALID || array.is_valid(i) {
+                    self.value_buffer
+                        .extend_from_slice(array.value(i).as_bytes());
+                }
+            }
+        }
+    }
+
+    fn append_offset(&mut self) {
+        let next_offset: i32 = self
+            .value_buffer
+            .len()
+            .try_into()
+            .expect("byte array offset overflow");
+        unsafe { self.offsets_buffer.push_unchecked(next_offset) };
+    }
+
+    fn finish(self, null_buffer: Option<NullBuffer>) -> StringArray {
+        let array_builder = ArrayDataBuilder::new(DataType::Utf8)
+            .len(self.offsets_buffer.len() / std::mem::size_of::<i32>() - 1)
+            .add_buffer(self.offsets_buffer.into())
+            .add_buffer(self.value_buffer.into())
+            .nulls(null_buffer);
+        let array_data = unsafe { array_builder.build_unchecked() };
+        StringArray::from(array_data)
+    }
+}
+
+pub fn concat2(args: &[ColumnarValue]) -> Result<ColumnarValue> {
+    let array_len = args
+        .iter()
+        .filter_map(|x| match x {
+            ColumnarValue::Array(array) => Some(array.len()),
+            _ => None,
+        })
+        .next();
+
+    // Scalar
+    if array_len.is_none() {
+        let mut result = String::new();
+        for arg in args {
+            if let ColumnarValue::Scalar(ScalarValue::Utf8(Some(v))) = arg {
+                result.push_str(v);
+            }
+        }
+        return Ok(ColumnarValue::Scalar(ScalarValue::Utf8(Some(result))));
+    }
+
+    // Array
+    let len = array_len.unwrap();
+    let mut data_size = 0;
+    let mut columns = Vec::with_capacity(args.len());
+
+    for arg in args {
+        match arg {
+            ColumnarValue::Scalar(ScalarValue::Utf8(maybe_value)) => {
+                if let Some(s) = maybe_value {
+                    data_size += s.len() * len;
+                    columns.push(ColumnarValueRef::Scalar(s.as_bytes()));
+                }
+            }
+            ColumnarValue::Array(array) => {
+                let string_array = as_string_array(array)?;
+                data_size += string_array.values().len();
+                columns.push(ColumnarValueRef::Array(string_array));
+            }
+            _ => unreachable!(),
+        }
+    }
+
+    let mut builder = StringArrayBuilder::with_capacity(len, data_size);
+    for i in 0..len {
+        columns
+            .iter()
+            .for_each(|column| builder.write::<true>(column, i));

Review Comment:
   You could also potentially special case when you know the null counts are 0 
(aka there are no nulls in the column) and you can avoid checking `is_null`



##########
datafusion/physical-expr/src/string_expressions.rs:
##########
@@ -227,6 +229,132 @@ pub fn concat(args: &[ColumnarValue]) -> 
Result<ColumnarValue> {
     }
 }
 
+enum ColumnarValueRef<'a> {
+    Scalar(&'a [u8]),
+    Array(&'a StringArray),
+}
+
+impl<'a> ColumnarValueRef<'a> {
+    #[inline]
+    fn is_valid(&self, i: usize) -> bool {
+        match &self {
+            Self::Scalar(_) => true,
+            Self::Array(array) => array.is_valid(i),
+        }
+    }
+
+    #[inline]
+    fn nulls(&self) -> Option<NullBuffer> {
+        match &self {
+            Self::Scalar(_) => None,
+            Self::Array(array) => array.nulls().map(|b| b.clone()),
+        }
+    }
+}
+
+struct StringArrayBuilder {

Review Comment:
   I think some comments that explained how this was different than 
https://docs.rs/arrow/latest/arrow/array/type.StringBuilder.html  would help. 
Maybe simply a note that it didn't check UTF8 again?
   
   I wonder if we could get the same effect by adding an `unsafe` function to 
`StringBuilder`, like
   
   ```rust
   /// Adds bytes to the in progress string, without checking for valid utf8
   /// 
   /// Safety: requires that bytes are valid utf8, otherwise an invalid 
StringArray will result
   unsafe fn append_unchecked(&mut self, bytes: &[u8]) 



##########
datafusion/physical-expr/benches/concat.rs:
##########
@@ -0,0 +1,50 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use arrow::util::bench_util::create_string_array_with_len;
+use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};
+use datafusion_common::ScalarValue;
+use datafusion_expr::ColumnarValue;
+use datafusion_physical_expr::string_expressions::{concat, concat2};
+use std::sync::Arc;
+
+fn create_args(size: usize, str_len: usize) -> Vec<ColumnarValue> {
+    let array = Arc::new(create_string_array_with_len::<i32>(size, 0.2, 
str_len));
+    let scalar = ScalarValue::Utf8(Some(", ".to_string()));
+    vec![
+        ColumnarValue::Array(array.clone()),
+        ColumnarValue::Scalar(scalar),
+        ColumnarValue::Array(array),
+    ]
+}
+
+fn criterion_benchmark(c: &mut Criterion) {
+    for size in [1024, 4096, 8192] {
+        let args = create_args(1024, 32);

Review Comment:
   did you mean to use `size` here too? Right now size seems only used for the 
name
   
   ```suggestion
           let args = create_args(size, 32);
   ```



-- 
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