加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – HttpContext.Current调用背后有多少计算?

发布时间:2020-12-16 07:07:16 所属栏目:asp.Net 来源:网络整理
导读:这个很贵吗? 我正在开发一个HtmlHelper,它直接呈现给Response.Output以保存不必要的字符串创建,我需要选择: % Validator.RenderClient(Response.Output); % 和 % Validator.RenderClient(); % 并从HttpContext.Current.Response获取textWriter 解决方法 @D
这个很贵吗?

我正在开发一个HtmlHelper,它直接呈现给Response.Output以保存不必要的字符串创建,我需要选择:

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

<% Validator.RenderClient(); %>

并从HttpContext.Current.Response获取textWriter

解决方法

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

它固定在周围:

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

无论如何,HttpContext.Current会造成一个重大的性能问题,你需要每次请求调用10000多个(成本主要由Response.Write调用组成).这很可能不会发生.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读