HttpContext.Current调用背后需要进行多少计算? [英] How much computation is behind a HttpContext.Current call?

查看:89
本文介绍了HttpContext.Current调用背后需要进行多少计算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

贵吗?

我正在开发一个直接呈现给Response.Output的HtmlHelper,以节省不必要的字符串创建,我需要在以下选项之间进行选择:

I am developing an HtmlHelper that renders directly to Response.Output in order to save unnecesary string creation and I need to choose between:

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

<% Validator.RenderClient(); %>

并从HttpContext.Current.Response获取textWriter

and get the textWriter from HttpContext.Current.Response

推荐答案

@道金斯

100次运行太少,您需要多次运行大约10000次并重复一次,然后取其平均值以得到可靠的结果.在您的示例中,误差幅度很大,但这是正确的方法.

100 runs is too few, you need to run about 10000 times several times and repeat it and then take the average of that to get a reliable result. The margin of error is to big in your example, but it's the right way to go.

这就是我所做的:

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%.

Your result show that there's a 18% performance difference, which shows that it's more expensive but it off by 8%.

我重新运行了几次,得出了10%的差异,误差幅度小于1%.

I re-ran the numbers several times and came up with a 10% difference with a error margin of less then 1%.

它稳定在周围:

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

无论如何,HttpContext.Current提出了一个严重的性能问题,您需要将其称为每个请求超过10000个(成本主要由Response.Write调用弥补).而且这可能不会发生.

Anyway, HttpContext.Current to pose a significant performance problem you'll need to call it way more than 10000 per request (the cost is largely made up by the Response.Write calls). And that's likely not going to happen.

这篇关于HttpContext.Current调用背后需要进行多少计算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆