Skip to content

perf: remove per-row String allocation from Spark soundex and quote#23880

Open
andygrove wants to merge 1 commit into
apache:mainfrom
andygrove:opt/spark-string-per-row-alloc
Open

perf: remove per-row String allocation from Spark soundex and quote#23880
andygrove wants to merge 1 commit into
apache:mainfrom
andygrove:opt/spark-string-per-row-alloc

Conversation

@andygrove

@andygrove andygrove commented Jul 25, 2026

Copy link
Copy Markdown
Member

Which issue does this PR close?

N/A

Rationale for this change

Spark's soundex and quote both allocated a fresh String for every row and
collected the results into a StringArray.

soundex allocated twice per row: once for the code buffer, and again for the
format!("{soundex_code:0<4}") that zero-pads it. quote allocated a String
sized to the input, then copied the input into it one char at 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. quote only ever wraps the
input 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) -> String becomes append_soundex(&mut StringBuilder, &str),
    building the four-character code in a [u8; 4] initialised to b'0' — which is
    the zero-padding, so the trailing format! disappears.
  • Strings that do not start with an ASCII letter are passed through unchanged;
    previously this path called s.to_string(), now it appends by reference.
  • The Utf8/LargeUtf8 and Utf8View entry points share one soundex_impl
    over Option<&str>, pre-sizing the builder at 4 bytes per row.

quote.rs:

  • compute_quote(&str) -> String becomes append_quoted(&mut StringBuilder, &str),
    writing into the builder's buffer via the fmt::Write impl and finalising with
    append_value("").
  • Escaping uses str::split('\'') to copy the runs between quotes in one memcpy
    each, instead of pushing every char individually.
  • The builder is pre-sized from the input's value_data() length plus two bytes
    per row for the surrounding quotes.

Output is unchanged in both cases.

Are these changes tested?

Existing coverage pins the behaviour: spark/string/soundex.slt and
spark/string/quote.slt assert concrete outputs, including the non-alphabetic
passthrough, codes shorter than four characters (padding), codes truncated at
four, and strings with and without embedded quotes. All 59 spark/string
sqllogictest files and the 258 datafusion-spark unit tests pass.

The benchmark used below, datafusion/spark/benches/soundex_quote.rs, is added
separately in #23882 so the baseline can be measured on main before this
change lands. It covers both functions over Utf8 and Utf8View at 1024 and
8192 rows with 20% nulls; the quote input is a mix of strings with and without
embedded quotes so the escaping path is exercised without dominating.

Benchmarks

Criterion, apache/main @ f1ab86dad as baseline. Median of the reported
change interval.

Benchmark 1024 8192
soundex/utf8 −52.9% −49.5%
soundex/utf8view −54.5% −50.2%
quote/utf8 −60.7% −61.5%
quote/utf8view −60.5% −61.3%

Are there any user-facing changes?

No. Both functions produce byte-identical output; this is purely an allocation
change.

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.
@andygrove
andygrove force-pushed the opt/spark-string-per-row-alloc branch from 812da2f to 3e80e81 Compare July 25, 2026 14:08
@codecov-commenter

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.66667% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 80.65%. Comparing base (f1ab86d) to head (3e80e81).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
datafusion/spark/src/function/string/soundex.rs 85.71% 2 Missing and 1 partial ⚠️
datafusion/spark/src/function/string/quote.rs 96.29% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #23880      +/-   ##
==========================================
- Coverage   80.65%   80.65%   -0.01%     
==========================================
  Files        1091     1091              
  Lines      371031   371040       +9     
  Branches   371031   371040       +9     
==========================================
+ Hits       299256   299257       +1     
- Misses      53935    53936       +1     
- Partials    17840    17847       +7     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@neilconway neilconway left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

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.

Ok(Arc::new(result) as ArrayRef)
Ok(quote_impl(
str_array.iter(),
str_array.get_buffer_memory_size(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like get_buffer_memory_size sums the buffer capacities, not their actual valid contents, so this will also over-allocate for sliced arrays.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants