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 <markfreeman@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
This commit is contained in:
Axel Wagner 2025-11-19 09:28:16 +01:00 committed by Sean Liao
parent 437323ef7b
commit a18294bb6a
4 changed files with 15 additions and 46 deletions

View file

@ -12,6 +12,7 @@ import (
"internal/runtime/atomic"
"internal/runtime/gc"
"internal/runtime/sys"
"math/bits"
"unsafe"
)
@ -181,12 +182,10 @@ func stackinit() {
// stacklog2 returns ⌊log_2(n)⌋.
func stacklog2(n uintptr) int {
log2 := 0
for n > 1 {
n >>= 1
log2++
if n == 0 {
return 0
}
return log2
return bits.Len64(uint64(n))
}
// Allocates a stack from the free pool. Must be called with