Skip to content

Faster Stdlib sort for short slices? #139133

Open
@leonardo-m

Description

@leonardo-m

Where I need to sort many (like 100_000) times a small number of numbers (here small means 0 ..= 12), the built-in sort has shown me to be slower than a basic Insertion Sort implementation like this (this needs T to be Copy for simplicity):

fn insertion_sort<T: Copy + PartialOrd>(data: &mut [T]) -> &mut [T] {
    for i in 1 .. data.len() {
        let aux = data[i];
        let mut j = i;
        while j > 0 && data[j - 1] > aux {
            data[j] = data[j - 1];
            j -= 1;
        }
        data[j] = aux;
    }
    data
}

So perhaps the Rust stdlib sort(s) could call code like this when the input is small (I think an extra lenght test isn't going to cause damages).

(I've also noticed that the built-in un unstable sort of u32s adds about 5.5 kbytes to my binary, while this little Insertion Sort adds very little to the binary. I think this "problem" can't be solved, unless you want to add something like a small_sort() to the stdlib that only contains a basic algorithm like that).

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-feature-requestCategory: A feature request, i.e: not implemented / a PR.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