是否昂貴?HttpContext.Current調用後有多少計算?
我正在開發直接呈現到Response.Output爲了節省unnecesary字符串創建一個的HtmlHelper,我需要之間做出選擇:
<% Validator.RenderClient(Response.Output); %>
和
<% Validator.RenderClient(); %>
,並從TextWriter的HttpContext.Current.Response
是否昂貴?HttpContext.Current調用後有多少計算?
我正在開發直接呈現到Response.Output爲了節省unnecesary字符串創建一個的HtmlHelper,我需要之間做出選擇:
<% Validator.RenderClient(Response.Output); %>
和
<% Validator.RenderClient(); %>
,並從TextWriter的HttpContext.Current.Response
@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(該費用由響應很大程度上彌補了一個顯著的性能問題。寫呼叫)。這很可能不會發生。
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;
}
...
所以有位穿 '東西' 回事;具體我不知道。
它根本不是密集型的。我不知道爲什麼我沒有嘗試這第一次:
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蜱
因此,它是相當快!
我與我們進行性能測試的方式有問題,請參閱下面的答案。您的答案是正確的,但結果不準確(統計可行)。 – 2010-01-08 13:38:36
出於某種原因,我覺得有趣的是,他們似乎更喜歡不合邏輯的調用上下文返回的邏輯調用上下文將返回什麼(無論那些東西)。 – 2008-11-14 18:40:45