65.9K
CodeProject 正在变化。 阅读更多。
Home

快速获取特定标头值的简便方法

starIconstarIconstarIconemptyStarIconemptyStarIcon

3.00/5 (1投票)

2009年3月18日

MIT
viewsIcon

28356

获取特定Header值的快速方法。

引言

本文介绍了一种获取特定Header值的快速方法。这只是 http://dotnetperls.com/Content/GZIP-Request.aspx 的一个更通用的版本。

虽然我的方法稍微慢一些(性能差异几乎可以忽略不计),但这样,你就不需要为所有可能的Header进行硬编码。我还尝试使用循环比较字符,但速度更慢。

使用代码

public static string GetHeaderValue(NameValueCollection headers, string key)
{
    for (int i = 0; i < headers.Count; i++)
    {
        if (string.Equals(headers.GetKey(i), key, 
            System.StringComparison.OrdinalIgnoreCase))
        {
            return headers.Get(i);
        }
    }

    return string.Empty;
}

例如,如果你想查找“Accept-Encoding”,只需调用 GetHeaderValue(request.Headers, "Accept-Encoding"),假设你有一个名为 request 的 HttpRequest 实例。

性能测试

将以下代码放入控制台程序即可

private static NameValueCollection headers = new NameValueCollection();
        
static void Main(string[] args)
{            
    Console.ReadLine();
    GetHeaderValuePerformanceTest();
    Console.ReadLine();
}

static void GetHeaderValuePerformanceTest()
{
    
    headers.Add("Content-Type", "application/json");
    headers.Add("Accept", "text/html,application/xhtml+xml," + 
                "application/xml;q=0.9,*/*;q=0.8");
    headers.Add("Accept-Language", "en-us,en;q=0.5");
    headers.Add("Accept-Encoding", "gzip");
    headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
    headers.Add("Connection", "keep-alive");

    int iterations = 1000000;
    Stopwatch watch;

    // GetHeaderValue
    watch = Stopwatch.StartNew();
    for (int i = 0; i < iterations; i++)
    {
        var result = GetHeaderValue(headers, "Accept-Encoding");
    }
    watch.Stop();
    Console.Write("GetHeaderValue: " + watch.ElapsedMilliseconds.ToString());
    Console.WriteLine();

    // Indexer
    watch = Stopwatch.StartNew();
    for (int i = 0; i < iterations; i++)
    {
        var result = headers["Accept-Encoding"];
    }

    watch.Stop();
    Console.Write("Indexer: " + watch.ElapsedMilliseconds.ToString());
    Console.WriteLine();
}

static string GetHeaderValue(NameValueCollection headers, string key)
{
    for (int i = 0; i < headers.Count; i++)
    {
        if (string.Equals(headers.GetKey(i), key, 
            System.StringComparison.OrdinalIgnoreCase))
        {
            return headers.Get(i);
        }
    }

    return string.Empty;
}

100万次循环的结果

GetHeaderValue:344ms
Indexer:1350ms

关注点

此方法很快将被添加到我的项目 Apprender.Common 2.6 中,该项目托管在 http://apprender.codeplex.com/

历史

  • 2009年3月17日:发布。
  • 2009年3月18日:添加了性能测试,更新了代码。
© . All rights reserved.