Commit afb7b67a authored by Rui Ueyama's avatar Rui Ueyama Committed by Brad Fitzpatrick

encoding/base64, encoding/base32: make DecodeString faster

Previously, an input string was stripped of newline
characters at the beginning of DecodeString and then passed
to Decode. Decode again tried to strip newline characters.
That's waste of time.

benchmark                 old MB/s     new MB/s  speedup
BenchmarkDecodeString        38.37        65.20    1.70x

LGTM=dave, bradfitz
R=golang-codereviews, dave, bradfitz
CC=golang-codereviews
https://golang.org/cl/91770051
parent f20e4d5e
......@@ -330,7 +330,7 @@ func (enc *Encoding) Decode(dst, src []byte) (n int, err error) {
func (enc *Encoding) DecodeString(s string) ([]byte, error) {
s = strings.Map(removeNewlinesMapper, s)
dbuf := make([]byte, enc.DecodedLen(len(s)))
n, err := enc.Decode(dbuf, []byte(s))
n, _, err := enc.decode(dbuf, []byte(s))
return dbuf[:n], err
}
......
......@@ -295,7 +295,7 @@ func (enc *Encoding) Decode(dst, src []byte) (n int, err error) {
func (enc *Encoding) DecodeString(s string) ([]byte, error) {
s = strings.Map(removeNewlinesMapper, s)
dbuf := make([]byte, enc.DecodedLen(len(s)))
n, err := enc.Decode(dbuf, []byte(s))
n, _, err := enc.decode(dbuf, []byte(s))
return dbuf[:n], err
}
......
......@@ -342,3 +342,11 @@ func TestDecoderIssue7733(t *testing.T) {
t.Errorf("DecodeString = %q; want abcd", s)
}
}
func BenchmarkDecodeString(b *testing.B) {
data := StdEncoding.EncodeToString(make([]byte, 8192))
b.SetBytes(int64(len(data)))
for i := 0; i < b.N; i++ {
StdEncoding.DecodeString(data)
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment