From c0eb7ab3062fae802639545770f6a897d75b0085 Mon Sep 17 00:00:00 2001 From: Julien Cretel Date: Mon, 12 May 2025 12:40:36 +0000 Subject: [PATCH] bytes, strings: micro-optimize EqualFold MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit The first loop leaves the lengths of the two arguments unchanged. Take advantage of this invariant in the loop's condition. Here are some benchmark results (no change to allocations): goos: darwin goarch: amd64 pkg: strings cpu: Intel(R) Core(TM) i7-6700HQ CPU @ 2.60GHz │ old │ new │ │ sec/op │ sec/op vs base │ EqualFold/Tests-8 240.0n ± 4% 245.1n ± 5% ~ (p=0.516 n=20) EqualFold/ASCII-8 11.50n ± 1% 11.04n ± 0% -3.96% (p=0.000 n=20) EqualFold/UnicodePrefix-8 102.1n ± 0% 102.2n ± 0% ~ (p=0.455 n=20) EqualFold/UnicodeSuffix-8 90.14n ± 0% 89.80n ± 1% ~ (p=0.113 n=20) geomean 71.00n 70.60n -0.56% Change-Id: I1f6d1df8a0398f9493692f59d7369c3f0fbba436 GitHub-Last-Rev: 9508ee26ad3cadcbb5e532a731b2553ba900f2b1 GitHub-Pull-Request: golang/go#73672 Reviewed-on: https://go-review.googlesource.com/c/go/+/671756 Reviewed-by: Michael Knyszek Reviewed-by: Keith Randall Reviewed-by: Keith Randall Auto-Submit: Keith Randall LUCI-TryBot-Result: Go LUCI --- src/bytes/bytes.go | 2 +- src/strings/strings.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/bytes/bytes.go b/src/bytes/bytes.go index 8198415c3e..a0a8fa0b29 100644 --- a/src/bytes/bytes.go +++ b/src/bytes/bytes.go @@ -1228,7 +1228,7 @@ func ReplaceAll(s, old, new []byte) []byte { func EqualFold(s, t []byte) bool { // ASCII fast path i := 0 - for ; i < len(s) && i < len(t); i++ { + for n := min(len(s), len(t)); i < n; i++ { sr := s[i] tr := t[i] if sr|tr >= utf8.RuneSelf { diff --git a/src/strings/strings.go b/src/strings/strings.go index d07a064228..d2cda74f68 100644 --- a/src/strings/strings.go +++ b/src/strings/strings.go @@ -1194,7 +1194,7 @@ func ReplaceAll(s, old, new string) string { func EqualFold(s, t string) bool { // ASCII fast path i := 0 - for ; i < len(s) && i < len(t); i++ { + for n := min(len(s), len(t)); i < n; i++ { sr := s[i] tr := t[i] if sr|tr >= utf8.RuneSelf { -- 2.51.0