Skip to content

Micro optimization idea: resue string buffer for FromIterator #51541

Closed
@Lucretiel

Description

@Lucretiel

rust/src/liballoc/string.rs

Lines 1720 to 1727 in 07c415c

#[stable(feature = "extend_string", since = "1.4.0")]
impl FromIterator<String> for String {
fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> String {
let mut buf = String::new();
buf.extend(iter);
buf
}
}

Basically the idea is that, for impl FromIterator<String> for String, we reimplement it slightly so that newly returned string reuses and reallocates the buffer of the first string in the iterator. It would look something like this:

fn from_iter(iter: I) -> String {
    match iter.next() {
        None => String::new(),
        Some(base) => { base.extend(iter); base }
    }
}

Of course, this might not be worth the added complexity– in particular, I'm not sure what the implications are for added branching– so I'm writing this issue to solicit any feedback before creating a PR.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions