Skip to content

Commit

Permalink
Rollup merge of rust-lang#55530 - ljedrz:speed_up_String_from_utf16, …
Browse files Browse the repository at this point in the history
…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.
  • Loading branch information
kennytm committed Nov 14, 2018
2 parents 27d0606 + 19aa101 commit 7982beb
Showing 1 changed file with 9 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/liballoc/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -618,7 +618,15 @@ impl String {
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
decode_utf16(v.iter().cloned()).collect::<Result<_, _>>().map_err(|_| FromUtf16Error(()))
let mut ret = String::with_capacity(v.len());
for c in decode_utf16(v.iter().cloned()) {
if let Ok(c) = c {
ret.push(c);
} else {
return Err(FromUtf16Error(()));
}
}
Ok(ret)
}

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

0 comments on commit 7982beb

Please sign in to comment.