]> Cypherpunks repositories - gostls13.git/commitdiff
net/textproto: eliminate some bounds checks
authorJulien Cretel <jub0bsinthecloud@gmail.com>
Sat, 23 Aug 2025 13:10:38 +0000 (13:10 +0000)
committerGopher Robot <gobot@golang.org>
Thu, 28 Aug 2025 08:55:11 +0000 (01:55 -0700)
This change lifts bounds checks out of loops in the trim function.
Here are some benchmark results (no change to allocations):

goos: darwin
goarch: amd64
pkg: net/textproto
cpu: Intel(R) Core(TM) i7-6700HQ CPU @ 2.60GHz
                                │     old     │                new                 │
                                │   sec/op    │   sec/op     vs base               │
ReadMIMEHeader/client_headers-8   3.531µ ± 3%   3.506µ ± 1%       ~ (p=0.068 n=20)
ReadMIMEHeader/server_headers-8   2.409µ ± 0%   2.384µ ± 1%  -1.02% (p=0.000 n=20)
Uncommon-8                        545.2n ± 1%   536.7n ± 0%  -1.58% (p=0.000 n=20)
geomean                           1.667µ        1.649µ       -1.10%

Change-Id: Ia6d4ac516497fd3521122ce9b97173a285b61e12
GitHub-Last-Rev: 580f35afceda1993da70a023ce5c28280bda1ff6
GitHub-Pull-Request: golang/go#75126
Reviewed-on: https://go-review.googlesource.com/c/go/+/698715
Reviewed-by: Cherry Mui <cherryyz@google.com>
Reviewed-by: Tobias Klauser <tobias.klauser@gmail.com>
Reviewed-by: Sean Liao <sean@liao.dev>
Auto-Submit: Sean Liao <sean@liao.dev>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Carlos Amedee <carlos@golang.org>
src/net/textproto/reader.go

index d375340121fa0b7d72e63330741d7eef76f3be5c..668c06c24c1372ac99c11255268ca711da8d64bf 100644 (file)
@@ -110,11 +110,12 @@ func trim(s []byte) []byte {
        for i < len(s) && (s[i] == ' ' || s[i] == '\t') {
                i++
        }
-       n := len(s)
-       for n > i && (s[n-1] == ' ' || s[n-1] == '\t') {
+       s = s[i:]
+       n := len(s) - 1
+       for n >= 0 && (s[n] == ' ' || s[n] == '\t') {
                n--
        }
-       return s[i:n]
+       return s[:n+1]
 }
 
 // ReadContinuedLineBytes is like [Reader.ReadContinuedLine] but