]> Cypherpunks repositories - gostls13.git/commitdiff
bytes: minor optimization to lastIndexFunc
authorBrad Fitzpatrick <bradfitz@golang.org>
Fri, 8 Feb 2013 00:00:06 +0000 (16:00 -0800)
committerBrad Fitzpatrick <bradfitz@golang.org>
Fri, 8 Feb 2013 00:00:06 +0000 (16:00 -0800)
Before and after:
BenchmarkTrimSpace  20000000   81.3 ns/op
BenchmarkTrimSpace  50000000   58.0 ns/op

(most whitespace trimming is ASCII whitespace)

Same optimization appeared a handful of other places
in this file, but not here.

R=golang-dev, dave
CC=golang-dev
https://golang.org/cl/7305063

src/pkg/bytes/bytes.go
src/pkg/bytes/bytes_test.go

index 31cf89ea87cc764711de02ef91a6f2bfb39858ad..6d40af4436c735d209f4ebdce2547d76ffb77b62 100644 (file)
@@ -571,7 +571,10 @@ func indexFunc(s []byte, f func(r rune) bool, truth bool) int {
 // inverted.
 func lastIndexFunc(s []byte, f func(r rune) bool, truth bool) int {
        for i := len(s); i > 0; {
-               r, size := utf8.DecodeLastRune(s[0:i])
+               r, size := rune(s[i-1]), 1
+               if r >= utf8.RuneSelf {
+                       r, size = utf8.DecodeLastRune(s[0:i])
+               }
                i -= size
                if f(r) == truth {
                        return i
index 1d073b143bd2b590e36574ec37cc2062a5652300..1d6274c33d1b67d314f0d3b51d6ab7e59436a70a 100644 (file)
@@ -1073,3 +1073,10 @@ func BenchmarkFieldsFunc(b *testing.B) {
                FieldsFunc(fieldsInput, unicode.IsSpace)
        }
 }
+
+func BenchmarkTrimSpace(b *testing.B) {
+       s := []byte("  Some text.  \n")
+       for i := 0; i < b.N; i++ {
+               TrimSpace(s)
+       }
+}