Skip to content

Commit 58a403a

Browse files
committed
better default capacity for str::replace
1 parent b27f33a commit 58a403a

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

library/alloc/src/str.rs

+8-3
Original file line numberDiff line numberDiff line change
@@ -270,7 +270,6 @@ impl str {
270270
#[inline]
271271
pub fn replace<P: Pattern>(&self, from: P, to: &str) -> String {
272272
// Fast path for ASCII to ASCII case.
273-
274273
if let Some(from_byte) = match from.as_utf8_pattern() {
275274
Some(Utf8Pattern::StringPattern([from_byte])) => Some(*from_byte),
276275
Some(Utf8Pattern::CharPattern(c)) => c.as_ascii().map(|ascii_char| ascii_char.to_u8()),
@@ -280,8 +279,14 @@ impl str {
280279
return unsafe { replace_ascii(self.as_bytes(), from_byte, *to_byte) };
281280
}
282281
}
283-
284-
let mut result = String::new();
282+
let to_len = to.as_bytes().len();
283+
// Set result capacity to self.len() when from.len() <= to.len()
284+
let default_capacity = match from.as_utf8_pattern() {
285+
Some(Utf8Pattern::StringPattern(s)) if s.len() <= to_len => self.len(),
286+
Some(Utf8Pattern::CharPattern(c)) if c.len_utf8() <= to_len => self.len(),
287+
_ => 0,
288+
};
289+
let mut result = String::with_capacity(default_capacity);
285290
let mut last_end = 0;
286291
for (start, part) in self.match_indices(from) {
287292
result.push_str(unsafe { self.get_unchecked(last_end..start) });

0 commit comments

Comments
 (0)