Skip to content
This repository has been archived by the owner on Feb 27, 2023. It is now read-only.

[v2] performance: Improve ParseSigned whitespace stripping #279

Merged
merged 2 commits into from
Nov 19, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 10 additions & 4 deletions encoding.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,12 @@ import (
"encoding/binary"
"io"
"math/big"
"regexp"
"strings"
"unicode"

"gopkg.in/square/go-jose.v2/json"
)

var stripWhitespaceRegex = regexp.MustCompile("\\s")

// Helper function to serialize known-good objects.
// Precondition: value is not a nil pointer.
func mustSerializeJSON(value interface{}) []byte {
Expand All @@ -56,7 +55,14 @@ func mustSerializeJSON(value interface{}) []byte {

// Strip all newlines and whitespace
func stripWhitespace(data string) string {
return stripWhitespaceRegex.ReplaceAllString(data, "")
buf := strings.Builder{}
buf.Grow(len(data))
for _, r := range data {
if !unicode.IsSpace(r) {
buf.WriteRune(r)
}
}
return buf.String()
}

// Perform compression based on algorithm
Expand Down
10 changes: 10 additions & 0 deletions signing_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -570,3 +570,13 @@ func TestSignerB64(t *testing.T) {
t.Errorf("Input/output do not match, got '%s', expected '%s'", output, input)
}
}

func BenchmarkParseSigned(b *testing.B) {
msg := `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c`
for i := 0; i < b.N; i++ {
_, err := ParseSigned(msg)
if err != nil {
b.Errorf("Error on parse: %s", err)
}
}
}