From 7e072199a6e650698c2f5f1e1053b20d48be43d3 Mon Sep 17 00:00:00 2001 From: Lukas Bergdoll Date: Fri, 10 Feb 2023 18:00:31 +0100 Subject: [PATCH] Speedup heapsort by 1.5x by making it branchless `slice::sort_unstable` will fall back to heapsort if it repeatedly fails to find a good pivot. By making the core child update code branchless it is much faster. On Zen3 sorting 10k `u64` and forcing the sort to pick heapsort, results in: 455us -> 278us --- library/core/src/slice/sort.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/library/core/src/slice/sort.rs b/library/core/src/slice/sort.rs index 2181f9a81185..990540f55f53 100644 --- a/library/core/src/slice/sort.rs +++ b/library/core/src/slice/sort.rs @@ -198,9 +198,7 @@ pub fn heapsort(v: &mut [T], mut is_less: F) } // Choose the greater child. - if child + 1 < v.len() && is_less(&v[child], &v[child + 1]) { - child += 1; - } + child += (child + 1 < v.len() && is_less(&v[child], &v[child + 1])) as usize; // Stop if the invariant holds at `node`. if !is_less(&v[node], &v[child]) {