1
Fork 0

Optimize FromIterator<OsString> to reuse the first allocation

This commit is contained in:
Ryan Lopopolo 2021-02-16 14:14:59 -08:00
parent 3ed6184434
commit 2fcb8b5c20
No known key found for this signature in database
GPG key ID: 46047D739B6AE0B1

View file

@ -1208,12 +1208,19 @@ impl<'a> Extend<&'a OsStr> for OsString {
impl FromIterator<OsString> for OsString { impl FromIterator<OsString> for OsString {
#[inline] #[inline]
fn from_iter<I: IntoIterator<Item = OsString>>(iter: I) -> Self { fn from_iter<I: IntoIterator<Item = OsString>>(iter: I) -> Self {
let mut buf = Self::new(); let mut iterator = iter.into_iter();
for s in iter {
buf.push(&s); // Because we're iterating over `OsString`s, we can avoid at least
} // one allocation by getting the first string from the iterator
// and appending to it all the subsequent strings.
match iterator.next() {
None => OsString::new(),
Some(mut buf) => {
buf.extend(iterator);
buf buf
} }
}
}
} }
#[stable(feature = "osstring_extend", since = "1.52.0")] #[stable(feature = "osstring_extend", since = "1.52.0")]