perf: remove per-row String allocation from Spark soundex and quote - #23880
perf: remove per-row String allocation from Spark soundex and quote#23880andygrove wants to merge 2 commits into
Conversation
Both functions built a fresh String for every row and collected the results into a StringArray. soundex allocated twice per row -- once for the code buffer and once more for the format! that zero-pads it -- and quote allocated a String sized to the input before copying it in character at a time. Neither needs to allocate. A soundex code is always exactly four ASCII characters, so it is built in a stack buffer. quote writes straight into the builder and copies the runs between quotes rather than one char at a time. soundex -50%, quote -61% against the benchmarks added in apache#23882.
812da2f to
3e80e81
Compare
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #23880 +/- ##
==========================================
+ Coverage 80.65% 80.67% +0.02%
==========================================
Files 1091 1095 +4
Lines 371031 372468 +1437
Branches 371031 372468 +1437
==========================================
+ Hits 299256 300495 +1239
- Misses 53935 54041 +106
- Partials 17840 17932 +92 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
neilconway
left a comment
There was a problem hiding this comment.
Overall looks reasonable!
| .map(|s| s.map(compute_quote)) | ||
| .collect::<StringArray>(); | ||
| Ok(Arc::new(result)) | ||
| Ok(quote_impl(str_array.iter(), str_array.value_data().len())) |
There was a problem hiding this comment.
str_array.value_data().len() will over-allocate for sliced arrays.
There was a problem hiding this comment.
Confirmed — GenericByteArray::slice clones the whole value_data buffer and narrows only the offsets, so this over-allocates by however much of the buffer the slice excludes. Now taking the length from the sliced offsets (last - first) in 4a7577f.
| Ok(Arc::new(result) as ArrayRef) | ||
| Ok(quote_impl( | ||
| str_array.iter(), | ||
| str_array.get_buffer_memory_size(), |
There was a problem hiding this comment.
Looks like get_buffer_memory_size sums the buffer capacities, not their actual valid contents, so this will also over-allocate for sliced arrays.
There was a problem hiding this comment.
Right, and it is wrong in the other direction too: strings of 12 bytes or fewer live inline in the views, so the data buffers can be near-empty while the array holds plenty of data. Switched to total_bytes_len(), which walks the sliced views and counts inlined values, in 4a7577f.
`value_data().len()` spans the entire values buffer even when the array is a slice, and `get_buffer_memory_size()` reports buffer capacities while ignoring inlined view values. Take the length from the sliced offsets and from `total_bytes_len()` instead.
| let data_len = match (offsets.first(), offsets.last()) { | ||
| (Some(first), Some(last)) => last.as_usize() - first.as_usize(), | ||
| _ => 0, | ||
| }; |
There was a problem hiding this comment.
offset buffers are guaranteed to be non-empty so we can unwrap instead of matching here
Which issue does this PR close?
N/A
Rationale for this change
Spark's
soundexandquoteboth allocated a freshStringfor every row andcollected the results into a
StringArray.soundexallocated twice per row: once for the code buffer, and again for theformat!("{soundex_code:0<4}")that zero-pads it.quoteallocated aStringsized to the input, then copied the input into it one
charat a time.Neither function needs to allocate per row. A soundex code is always exactly
four ASCII characters, so it fits in a stack buffer.
quoteonly ever wraps theinput and escapes embedded quotes, so it can write straight into the output
buffer and copy the runs between quotes rather than character by character.
What changes are included in this PR?
soundex.rs:compute_soundex(&str) -> Stringbecomesappend_soundex(&mut StringBuilder, &str),building the four-character code in a
[u8; 4]initialised tob'0'— which isthe zero-padding, so the trailing
format!disappears.previously this path called
s.to_string(), now it appends by reference.Utf8/LargeUtf8andUtf8Viewentry points share onesoundex_implover
Option<&str>, pre-sizing the builder at 4 bytes per row.quote.rs:compute_quote(&str) -> Stringbecomesappend_quoted(&mut StringBuilder, &str),writing into the builder's buffer via the
fmt::Writeimpl and finalising withappend_value("").str::split('\'')to copy the runs between quotes in one memcpyeach, instead of pushing every
charindividually.value_data()length plus two bytesper row for the surrounding quotes.
Output is unchanged in both cases.
Are these changes tested?
Existing coverage pins the behaviour:
spark/string/soundex.sltandspark/string/quote.sltassert concrete outputs, including the non-alphabeticpassthrough, codes shorter than four characters (padding), codes truncated at
four, and strings with and without embedded quotes. All 59
spark/stringsqllogictest files and the 258
datafusion-sparkunit tests pass.The benchmark used below,
datafusion/spark/benches/soundex_quote.rs, is addedseparately in #23882 so the baseline can be measured on
mainbefore thischange lands. It covers both functions over
Utf8andUtf8Viewat 1024 and8192 rows with 20% nulls; the
quoteinput is a mix of strings with and withoutembedded quotes so the escaping path is exercised without dominating.
Benchmarks
Criterion,
apache/main@f1ab86dadas baseline. Median of the reportedchange interval.
soundex/utf8soundex/utf8viewquote/utf8quote/utf8viewAre there any user-facing changes?
No. Both functions produce byte-identical output; this is purely an allocation
change.