From 97b0288365c5cb4da1c0e5714ce7d5a0c4cd752e Mon Sep 17 00:00:00 2001 From: Jonathan Hallstrom Date: Sun, 15 Sep 2024 13:28:33 +0200 Subject: [PATCH] make partitionPoint faster by making it branchless --- lib/std/sort.zig | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/lib/std/sort.zig b/lib/std/sort.zig index 23707f138591..14ce4dde00d9 100644 --- a/lib/std/sort.zig +++ b/lib/std/sort.zig @@ -678,18 +678,23 @@ pub fn partitionPoint( context: anytype, comptime predicate: fn (@TypeOf(context), T) bool, ) usize { - var low: usize = 0; - var high: usize = items.len; + var it: usize = 0; + var len: usize = items.len; - while (low < high) { - const mid = low + (high - low) / 2; - if (predicate(context, items[mid])) { - low = mid + 1; - } else { - high = mid; + while (len > 1) { + const half: usize = len / 2; + len -= half; + if (predicate(context, items[it + half - 1])) { + @branchHint(.unpredictable); + it += half; } } - return low; + + if (it < items.len) { + it += @intFromBool(predicate(context, items[it])); + } + + return it; } test partitionPoint {