-
Notifications
You must be signed in to change notification settings - Fork 2.3k
perf: remove per-row String allocation from Spark soundex and quote #23880
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
andygrove
wants to merge
1
commit into
apache:main
Choose a base branch
from
andygrove:opt/spark-string-per-row-alloc
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+81
−41
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -15,7 +15,7 @@ | |
| // specific language governing permissions and limitations | ||
| // under the License. | ||
|
|
||
| use arrow::array::{ArrayRef, OffsetSizeTrait, StringArray}; | ||
| use arrow::array::{Array, ArrayRef, OffsetSizeTrait, StringBuilder}; | ||
| use arrow::datatypes::DataType; | ||
| use datafusion::logical_expr::{Coercion, ColumnarValue, Signature, TypeSignatureClass}; | ||
| use datafusion_common::cast::{as_generic_string_array, as_string_view_array}; | ||
|
|
@@ -25,6 +25,7 @@ use datafusion_common::{Result, exec_err}; | |
| use datafusion_expr::{ScalarFunctionArgs, ScalarUDFImpl, Volatility}; | ||
| use datafusion_functions::utils::make_scalar_function; | ||
|
|
||
| use std::fmt::Write; | ||
| use std::sync::Arc; | ||
|
|
||
| /// Spark-compatible `quote` expression | ||
|
|
@@ -88,34 +89,55 @@ fn spark_quote_inner(arg: &[ArrayRef]) -> Result<ArrayRef> { | |
|
|
||
| fn quote_array<T: OffsetSizeTrait>(array: &ArrayRef) -> Result<ArrayRef> { | ||
| let str_array = as_generic_string_array::<T>(array)?; | ||
| let result = str_array | ||
| .iter() | ||
| .map(|s| s.map(compute_quote)) | ||
| .collect::<StringArray>(); | ||
| Ok(Arc::new(result)) | ||
| Ok(quote_impl(str_array.iter(), str_array.value_data().len())) | ||
| } | ||
|
|
||
| fn quote_view(str_view: &ArrayRef) -> Result<ArrayRef> { | ||
| let str_array = as_string_view_array(str_view)?; | ||
| let result = str_array | ||
| .iter() | ||
| .map(|opt_str| opt_str.map(compute_quote)) | ||
| .collect::<StringArray>(); | ||
| Ok(Arc::new(result) as ArrayRef) | ||
| Ok(quote_impl( | ||
| str_array.iter(), | ||
| str_array.get_buffer_memory_size(), | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Looks like |
||
| )) | ||
| } | ||
|
|
||
| const QUOTE_CHAR: char = '\''; | ||
| const ESCAPE_CHAR: char = '\\'; | ||
| /// A literal quote in the input is emitted as this two-character escape. | ||
| const ESCAPED_QUOTE: &str = "\\'"; | ||
|
|
||
| fn compute_quote(s: &str) -> String { | ||
| let mut quoted = String::with_capacity(s.len() + 2); | ||
| quoted.push(QUOTE_CHAR); | ||
| for c in s.chars() { | ||
| if c == QUOTE_CHAR { | ||
| quoted.push(ESCAPE_CHAR); | ||
| /// Quotes every value, writing directly into the output buffer. | ||
| /// | ||
| /// `data_capacity` is a hint for the total input byte length; the output adds two | ||
| /// surrounding quotes per row plus one byte per escaped quote. | ||
| fn quote_impl<'a>( | ||
| input: impl Iterator<Item = Option<&'a str>>, | ||
| data_capacity: usize, | ||
| ) -> ArrayRef { | ||
| let len = input.size_hint().0; | ||
| let mut builder = StringBuilder::with_capacity(len, data_capacity + 2 * len); | ||
| for value in input { | ||
| match value { | ||
| Some(value) => append_quoted(&mut builder, value), | ||
| None => builder.append_null(), | ||
| } | ||
| quoted.push(c); | ||
| } | ||
| quoted.push(QUOTE_CHAR); | ||
| quoted | ||
| Arc::new(builder.finish()) | ||
| } | ||
|
|
||
| /// Appends `s` wrapped in single quotes, with any embedded quote backslash-escaped. | ||
| /// | ||
| /// Writes straight into the builder's buffer — finalized by the trailing | ||
| /// `append_value("")` — so no intermediate `String` is allocated per row, and | ||
| /// copies the runs between quotes rather than one character at a time. | ||
| fn append_quoted(builder: &mut StringBuilder, s: &str) { | ||
| // `write_str` on a `GenericStringBuilder` is infallible. | ||
| let mut runs = s.split(QUOTE_CHAR); | ||
| builder.write_char(QUOTE_CHAR).unwrap(); | ||
| // `split` always yields at least one run. | ||
| builder.write_str(runs.next().unwrap_or_default()).unwrap(); | ||
| for run in runs { | ||
| builder.write_str(ESCAPED_QUOTE).unwrap(); | ||
| builder.write_str(run).unwrap(); | ||
| } | ||
| builder.write_char(QUOTE_CHAR).unwrap(); | ||
| builder.append_value(""); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
str_array.value_data().len()will over-allocate for sliced arrays.