2008-11-14 50 views
5

是否昂贵?HttpContext.Current调用后有多少计算?

我正在开发直接呈现到Response.Output为了节省unnecesary字符串创建一个的HtmlHelper,我需要之间做出选择:

<% Validator.RenderClient(Response.Output); %> 

<% Validator.RenderClient(); %> 

,并从TextWriter的HttpContext.Current.Response

回答

3

@Dawkins

100次太少,你需要运行约10000倍几次重复再取,平均得到可靠的结果。在你的例子中,误差幅度很大,但这是正确的路要走。

这里就是我所做的:

var results1 = new List<long>(); 
var results2 = new List<long>(); 

for (int j = 0; j < 100; j++) 
{ 
    var sp = new System.Diagnostics.Stopwatch(); 

    // With HttpContext.Current: 
    sp.Start(); 
    for (int i = 0; i < 10000; i++) 
    { 
     HttpContext.Current.Response.Output.Write(i); 
    } 
    sp.Stop(); 

    results1.Add(sp.ElapsedTicks); 

    // Without: 
    TextWriter output2 = HttpContext.Current.Response.Output; 
    sp.Reset(); 

    sp.Start(); 
    for (int i = 0; i < 10000; i++) 
    { 
     output2.Write(i); 
    } 
    sp.Stop(); 

    HttpContext.Current.Response.Clear(); 

    results2.Add(sp.ElapsedTicks); 
} 

results1.Sort(); 
results2.Sort(); 

HttpContext.Current.Response.Write(string.Format("HttpContext.Current={0:0.000}ms, Local variable={1:0.000}ms, R={2:0.0%}<br/>", results1[results1.Count/2]/(double)TimeSpan.TicksPerMillisecond, results2[results2.Count/2]/(double)TimeSpan.TicksPerMillisecond, (double)results1[results1.Count/2]/(double)results2[results2.Count/2])); 

你的结果表明,有18%的性能差异,这表明它更昂贵,但它关闭了8%。

我重新运行了数次,结果出现了10%的差异,误差小于1%。

它stablaizes各地:

HttpContext.Current=0,536ms, Local variable=0,486ms, R=110,2% 

反正HttpContext.Current摆姿势,你需要调用它每个请求的方式超过10000(该费用由响应很大程度上弥补了一个显著的性能问题。写呼叫)。这很可能不会发生。

2

from reflector

public static HttpContext get_Current() 
{ 
    return (ContextBase.Current as HttpContext); 
} 

电话ContextBase 这就要求

public static object HostContext 
{ 
    get 
    { 
     object hostContext = 
      Thread.CurrentThread.GetIllogicalCallContext().HostContext; 
     if (hostContext == null) 
     { 
      hostContext = GetLogicalCallContext().HostContext; 
     } 
     return hostContext; 
    } 

...

所以有位穿 '东西' 回事;具体我不知道。

+4

出于某种原因,我觉得有趣的是,他们似乎更喜欢不合逻辑的调用上下文返回的逻辑调用上下文将返回什么(无论那些东西)。 – 2008-11-14 18:40:45

2

它根本不是密集型的。我不知道为什么我没有尝试这第一次:

 System.Diagnostics.Stopwatch sp = new System.Diagnostics.Stopwatch(); 

     // With HttpContext.Current: 
     sp.Start(); 
     for (int i = 0; i < 100; i++) 
     { 
      HttpContext.Current.Response.Output.Write(i.ToString()); 
     } 
     sp.Stop(); 
     long result1 = sp.ElapsedTicks; 

     // Without: 
     TextWriter output2 = HttpContext.Current.Response.Output; 
     sp.Reset(); 
     sp.Start(); 
     for (int i = 0; i < 100; i++) 
     { 
      output2.Write(i.ToString()); 
     } 
     sp.Stop(); 
     long result2 = sp.ElapsedTicks; 

而且我的电脑的结果是围绕:

RESULT1 = 395蜱 RESULT2 = 332蜱

因此,它是相当快!

+0

我与我们进行性能测试的方式有问题,请参阅下面的答案。您的答案是正确的,但结果不准确(统计可行)。 – 2010-01-08 13:38:36