From 28a6a16d212b8c31eb5710cba752c931676cd8db Mon Sep 17 00:00:00 2001 From: Alexander Yastrebov Date: Tue, 27 Feb 2024 12:59:47 +0100 Subject: [PATCH] jwt: benchmark Parse MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ``` $ benchstat <(go test ./jwt -run=NONE -bench=BenchmarkParse -count=10) goos: linux goarch: amd64 pkg: github.com/zalando/skipper/jwt cpu: Intel(R) Core(TM) i5-8350U CPU @ 1.70GHz │ /dev/fd/63 │ │ sec/op │ Parse-8 13.53µ ± 8% │ /dev/fd/63 │ │ B/op │ Parse-8 1.656Ki ± 0% │ /dev/fd/63 │ │ allocs/op │ Parse-8 40.00 ± 0% ``` Signed-off-by: Alexander Yastrebov --- jwt/token_test.go | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/jwt/token_test.go b/jwt/token_test.go index 7669ff664e..2fbc1f16e8 100644 --- a/jwt/token_test.go +++ b/jwt/token_test.go @@ -4,6 +4,7 @@ import ( "encoding/base64" "encoding/json" "reflect" + "strings" "testing" ) @@ -57,10 +58,38 @@ func TestParse(t *testing.T) { } } -func marshalBase64JSON(t *testing.T, v interface{}) string { +func marshalBase64JSON(tb testing.TB, v interface{}) string { d, err := json.Marshal(v) if err != nil { - t.Fatalf("failed to marshal json: %v, %v", v, err) + tb.Fatalf("failed to marshal json: %v, %v", v, err) } return base64.RawURLEncoding.EncodeToString(d) } + +var parseSink *Token + +func BenchmarkParse(b *testing.B) { + claims := map[string]interface{}{ + "azp": strings.Repeat("z", 100), + "exp": 1234567890, + "aaaaaaaaaaaaaaaaaaaaaa": strings.Repeat("a", 40), + "bbbbbbbbbbbbbbbbbbbbbb": strings.Repeat("b", 40), + "cccccccccccccccccccccc": strings.Repeat("c", 40), + "iat": 1234567890, + "iss": "https://skipper.identity.example.org", + "sub": "foo_bar-baz-qux", + } + + value := strings.Repeat("x", 64) + "." + marshalBase64JSON(b, claims) + "." + strings.Repeat("x", 128) + + _, err := Parse(value) + if err != nil { + b.Fatal(err) + } + + b.ResetTimer() + b.ReportAllocs() + for i := 0; i < b.N; i++ { + parseSink, _ = Parse(value) + } +}