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

Commit

Permalink
Merge pull request #279 from pquerna/pq/perf_parse_signed
Browse files Browse the repository at this point in the history
[v2] performance: Improve ParseSigned whitespace stripping
  • Loading branch information
csstaub committed Nov 19, 2019
2 parents 8fd82ff + 5b063f6 commit f518123
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
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)
}
}
}

0 comments on commit f518123

Please sign in to comment.