[Performance] Low hanging fruit in Tokens.JWT #1955
Labels
Customer reported
Indicates issue was opened by customer
Design
The issue is large enough that we need a design
Enhancement
The issue is a new feature
Recently while comparing a benchmark that didn't use auth and one that used jwt auth I noticed the allocations were extremely high when using jwt. Digging into it I found many places where allocations could be improved in System.IdentityModel.Tokens.Jwt, I'll focus on the largest allocation I saw for this issue.
Our code first checks if we the token can be read via
azure-activedirectory-identitymodel-extensions-for-dotnet/src/System.IdentityModel.Tokens.Jwt/JwtSecurityTokenHandler.cs
Line 278 in b7a4fdd
Then it proceeds to call
ValidateToken
azure-activedirectory-identitymodel-extensions-for-dotnet/src/System.IdentityModel.Tokens.Jwt/JwtSecurityTokenHandler.cs
Line 835 in b7a4fdd
Both these methods call
string.Split
on the provided token, check how many values are in the array, and then throw away the results.azure-activedirectory-identitymodel-extensions-for-dotnet/src/System.IdentityModel.Tokens.Jwt/JwtSecurityTokenHandler.cs
Lines 292 to 293 in b7a4fdd
Trying out a quick test to count the
'.'
characters in a string (then adding 1 to count the segments) shows we can do it allocation free and almost 6 times faster:Benchmark code
And since there are at least 2 calls to
string.Split
per request in the scenario I'm looking at, it would be even bigger savings!Proposal
string.Split
, could even try to vectorize 😄string.Split
is used just for the length of the output arrayThe text was updated successfully, but these errors were encountered: