Skip to content

Commit 3b40434

Browse files
authored
Rollup merge of rust-lang#55530 - ljedrz:speed_up_String_from_utf16, r=SimonSapin
Speed up String::from_utf16 Collecting into a `Result` is idiomatic, but not necessarily fast due to rustc not being able to preallocate for the resulting collection. This is fine in case of an error, but IMO we should optimize for the common case, i.e. a successful conversion. This changes the behavior of `String::from_utf16` from collecting into a `Result` to pushing to a preallocated `String` in a loop. According to [my simple benchmark](https://gist.github.com/ljedrz/953a3fb74058806519bd4d640d6f65ae) this change makes `String::from_utf16` around **twice** as fast.
2 parents d7c833b + 19aa101 commit 3b40434

File tree

1 file changed

+9
-1
lines changed

1 file changed

+9
-1
lines changed

Diff for: src/liballoc/string.rs

+9-1
Original file line numberDiff line numberDiff line change
@@ -618,7 +618,15 @@ impl String {
618618
/// ```
619619
#[stable(feature = "rust1", since = "1.0.0")]
620620
pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
621-
decode_utf16(v.iter().cloned()).collect::<Result<_, _>>().map_err(|_| FromUtf16Error(()))
621+
let mut ret = String::with_capacity(v.len());
622+
for c in decode_utf16(v.iter().cloned()) {
623+
if let Ok(c) = c {
624+
ret.push(c);
625+
} else {
626+
return Err(FromUtf16Error(()));
627+
}
628+
}
629+
Ok(ret)
622630
}
623631

624632
/// Decode a UTF-16 encoded slice `v` into a `String`, replacing

0 commit comments

Comments
 (0)