Skip to content

Vec::splice() has noticeable overhead for some use cases #83266

Open
@adrian17

Description

@adrian17

As far as I know, Vec::splice() is the only way to extend the Vec from a slice in an arbitrary location. However, being a fairly universal api makes it slower than a hypothetical dedicated insert_from_slice could be.

In fact, according to cargo bench, for small vectors (let's say under 10) and number of elements to insert, it can be faster to insert them in a loop:

    for i in 0..5 { data.insert(3, 77); }

than to call splice:

    let new = [77; 5];
    data.splice(3..3, new.iter().copied());

splice also seems to optimize badly in presence of constants. For example, looking at Godbolt, the optimizer can't seem to optimize

    let tab = [77; 1];
    vec.splice(5..6, tab.iter().cloned());

as good as

    vec[5] = 77;

Or

    let tab = [77; 1];
    vec.splice(5..5, tab.iter().cloned());

as good as

    vec.insert(5, 77);

It'd be nice if the function had lower overhead for small vectors/slices. Or maybe if another specialized method insert_from_slice(idx, slice) was added that avoids all overhead for this particular use case.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-collectionsArea: `std::collections`C-enhancementCategory: An issue proposing an enhancement or a PR with one.I-slowIssue: Problems and improvements with respect to performance of generated code.T-libsRelevant to the library team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions