Skip to content

Commit 7982beb

Browse files
committed
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 27d0606 + 19aa101 commit 7982beb

File tree

1 file changed

+9
-1
lines changed

1 file changed

+9
-1
lines changed

src/liballoc/string.rs

Lines changed: 9 additions & 1 deletion
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)