Apache DataFusion SQL Query Engine
perf: Optimize replace() fastpath by avoiding alloc (#20344)
Neil Conway3f3860927702
diff --git a/datafusion/functions/src/string/replace.rs b/datafusion/functions/src/string/replace.rsindex 165e0634a6..458b86d0c6 100644--- a/datafusion/functions/src/string/replace.rs+++ b/datafusion/functions/src/string/replace.rs@@ -228,19 +228,21 @@ fn replace_into_string(buffer: &mut String, string: &str, from: &str, to: &str)return;}- // Fast path for replacing a single ASCII character with another single ASCII character- // This matches Rust's str::replace() optimization and enables vectorization+ // Fast path for replacing a single ASCII character with another single ASCII character.+ // Extends the buffer's underlying Vec<u8> directly, for performance.if let ([from_byte], [to_byte]) = (from.as_bytes(), to.as_bytes())&& from_byte.is_ascii()&& to_byte.is_ascii(){- // SAFETY: We're replacing ASCII with ASCII, which preserves UTF-8 validity- let replaced: Vec<u8> = string- .as_bytes()- .iter()- .map(|b| if *b == *from_byte { *to_byte } else { *b })- .collect();- buffer.push_str(unsafe { std::str::from_utf8_unchecked(&replaced) });+ // SAFETY: Replacing an ASCII byte with another ASCII byte preserves UTF-8 validity.+ unsafe {+ buffer.as_mut_vec().extend(+ string+ .as_bytes()+ .iter()+ .map(|&b| if b == *from_byte { *to_byte } else { b }),+ );+ }return;}