@@ -14,28 +14,26 @@ public static class HttpUserAgentParser
1414
1515{
1616 /// <summary>
17- /// Parses given <param name="userAgent"> user agent</param>
17+ /// Parses given user agent string without allocating a copy. Prefer this overload to avoid ToString() allocations.
1818 /// </summary>
19- public static HttpUserAgentInformation Parse ( ReadOnlySpan < char > userAgent )
19+ public static HttpUserAgentInformation Parse ( string userAgent )
2020 {
21- // prepare
22- userAgent = Cleanup ( userAgent ) ;
21+ ReadOnlySpan < char > span = Cleanup ( userAgent . AsSpan ( ) ) ;
2322
24- // analyze
25- if ( TryGetRobot ( userAgent , out string ? robotName ) )
23+ if ( TryGetRobot ( span , out string ? robotName ) )
2624 {
27- return HttpUserAgentInformation . CreateForRobot ( userAgent . ToString ( ) , robotName ) ;
25+ return HttpUserAgentInformation . CreateForRobot ( userAgent , robotName ) ;
2826 }
2927
30- HttpUserAgentPlatformInformation ? platform = GetPlatform ( userAgent ) ;
31- string ? mobileDeviceType = GetMobileDevice ( userAgent ) ;
28+ HttpUserAgentPlatformInformation ? platform = GetPlatform ( span ) ;
29+ string ? mobileDeviceType = GetMobileDevice ( span ) ;
3230
33- if ( TryGetBrowser ( userAgent , out ( string Name , string ? Version ) ? browser ) )
31+ if ( TryGetBrowser ( span , out ( string Name , string ? Version ) ? browser ) )
3432 {
35- return HttpUserAgentInformation . CreateForBrowser ( userAgent . ToString ( ) , platform , browser ? . Name , browser ? . Version , mobileDeviceType ) ;
33+ return HttpUserAgentInformation . CreateForBrowser ( userAgent , platform , browser ? . Name , browser ? . Version , mobileDeviceType ) ;
3634 }
3735
38- return HttpUserAgentInformation . CreateForUnknown ( userAgent . ToString ( ) , platform , mobileDeviceType ) ;
36+ return HttpUserAgentInformation . CreateForUnknown ( userAgent , platform , mobileDeviceType ) ;
3937 }
4038
4139 /// <summary>
@@ -105,7 +103,8 @@ public static (string Name, string? Version)? GetBrowser(ReadOnlySpan<char> user
105103 string ? version = null ;
106104 if ( TryExtractVersion ( userAgent , versionSearchStart , out Range range ) )
107105 {
108- version = userAgent . ToString ( ) ;
106+ // Only allocate the version substring, not the whole user agent
107+ version = userAgent [ range ] . ToString ( ) ;
109108 }
110109
111110 return ( rule . Name , version ) ;
0 commit comments