Permalink
Browse files

Perf: improve conneg accept header sorting

- only sort if there are more than 1 items
- comparer fast path when comparing the same instance
  • Loading branch information...
1 parent 38b159c commit e43ac2e49fd05d96db51c9be200f05c0d3a30cea @marcind marcind committed Apr 9, 2012
@@ -360,9 +360,7 @@ internal bool TryMatchSupportedMediaType(HttpRequestMessage request, out MediaTy
{
Contract.Assert(request != null);
- // Sort accept headers in descending order based on q factor.
- IEnumerable<MediaTypeWithQualityHeaderValue> acceptMediaTypeValues =
- request.Headers.Accept.OrderByDescending(m => m, MediaTypeWithQualityHeaderValueComparer.QualityComparer);
+ IEnumerable<MediaTypeWithQualityHeaderValue> acceptMediaTypeValues = SortByQFactor(request.Headers.Accept);
foreach (MediaTypeHeaderValue acceptMediaTypeValue in acceptMediaTypeValues)
{
@@ -376,6 +374,21 @@ internal bool TryMatchSupportedMediaType(HttpRequestMessage request, out MediaTy
return false;
}
+ private static IEnumerable<MediaTypeWithQualityHeaderValue> SortByQFactor(HttpHeaderValueCollection<MediaTypeWithQualityHeaderValue> acceptHeaders)
+ {
+ if (acceptHeaders.Count > 1)
+ {
+ // Sort accept headers (if more than 1) in descending order based on q factor
+ // Use OrderBy() instead of Array.Sort() as it performs fewer comparisons. In this case the comparisons
+ // are quite expensive so OrderBy() performs better.
+ return acceptHeaders.OrderByDescending(m => m, MediaTypeWithQualityHeaderValueComparer.QualityComparer);
+ }
+ else
+ {
+ return acceptHeaders;
+ }
+ }
+
internal bool TryMatchMediaTypeMapping(HttpRequestMessage request, out MediaTypeMatch mediaTypeMatch)
{
Contract.Assert(request != null, "request cannot be null.");
@@ -38,6 +38,11 @@ public int Compare(MediaTypeWithQualityHeaderValue mediaType1, MediaTypeWithQual
Contract.Assert(mediaType1 != null, "The 'mediaType1' parameter should not be null.");
Contract.Assert(mediaType2 != null, "The 'mediaType2' parameter should not be null.");
+ if (Object.ReferenceEquals(mediaType1, mediaType2))
+ {
+ return 0;
+ }
+
int returnValue = CompareBasedOnQualityFactor(mediaType1, mediaType2);
if (returnValue == 0)

0 comments on commit e43ac2e

Please sign in to comment.