From a18294bb6aa8f0dd656f2bcb6742f9de2936d0dc Mon Sep 17 00:00:00 2001 From: Axel Wagner Date: Wed, 19 Nov 2025 09:28:16 +0100 Subject: cmd/internal/obj/arm64, image/gif, runtime, sort: use math/bits to calculate log2 In several places the integer log2 is calculated using loops or similar mechanisms. math/bits.Len* provide a simpler and more efficient mechanisms for this. Annoyingly, every usage has slightly different ideas of what "log2" means and how non-positive inputs should be handled. I verified the replacements in each case by comparing the result for inputs from 0 to 1<<16. Change-Id: Ie962a74674802da363e0038d34c06979ccb41cf3 Reviewed-on: https://go-review.googlesource.com/c/go/+/721880 Reviewed-by: Mark Freeman LUCI-TryBot-Result: Go LUCI Reviewed-by: Michael Knyszek --- src/sort/search_test.go | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) (limited to 'src/sort') diff --git a/src/sort/search_test.go b/src/sort/search_test.go index 49813eaecb..b6ab900abe 100644 --- a/src/sort/search_test.go +++ b/src/sort/search_test.go @@ -5,6 +5,7 @@ package sort_test import ( + "math/bits" "runtime" . "sort" stringspkg "strings" @@ -135,13 +136,10 @@ func TestFind(t *testing.T) { // log2 computes the binary logarithm of x, rounded up to the next integer. // (log2(0) == 0, log2(1) == 0, log2(2) == 1, log2(3) == 2, etc.) func log2(x int) int { - n := 0 - for p := 1; p < x; p += p { - // p == 2**n - n++ + if x < 1 { + return 0 } - // p/2 < x <= p == 2**n - return n + return bits.Len(uint(x - 1)) } func TestSearchEfficiency(t *testing.T) { -- cgit v1.3-5-g9baa