How much computation is behind the HttpContext.Current call?

It is expensive?

I am developing an HtmlHelper that displays Response.Output directly to save unnecessary line creation, and I need to choose between:

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

and

<% Validator.RenderClient(); %>

and get textWriter from HttpContext.Current.Response

+5
source share
3 answers

@Dawkins

100 starts is too small, you need to run about 10,000 times several times and repeat it, and then take the average value to get a reliable result. The error limit in your example is large, but it is the right way.

Here is what I did:

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]));

Your result shows that the difference in performance is 18%, which shows that it is more expensive, but it is 8%.

10% - 1%.

:

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

, HttpContext.Current, , 10000 ( ​​ Response.Write). .

+3

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;
    }

...

""; .

+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 ticks

, !

+2

All Articles