Skip to content

Commit 2fcb8b5

Browse files
committed
Optimize FromIterator<OsString> to reuse the first allocation
1 parent 3ed6184 commit 2fcb8b5

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

library/std/src/ffi/os_str.rs

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1208,11 +1208,18 @@ impl<'a> Extend<&'a OsStr> for OsString {
12081208
impl FromIterator<OsString> for OsString {
12091209
#[inline]
12101210
fn from_iter<I: IntoIterator<Item = OsString>>(iter: I) -> Self {
1211-
let mut buf = Self::new();
1212-
for s in iter {
1213-
buf.push(&s);
1211+
let mut iterator = iter.into_iter();
1212+
1213+
// Because we're iterating over `OsString`s, we can avoid at least
1214+
// one allocation by getting the first string from the iterator
1215+
// and appending to it all the subsequent strings.
1216+
match iterator.next() {
1217+
None => OsString::new(),
1218+
Some(mut buf) => {
1219+
buf.extend(iterator);
1220+
buf
1221+
}
12141222
}
1215-
buf
12161223
}
12171224
}
12181225

0 commit comments

Comments
 (0)