.NET性能分析利器 : CLR Profiler的使用

转自: http://blog.csdn.net/chen_xizhang/article/details/5952416

http://msdn.microsoft.com/zh-cn/library/ms979205(en-us).aspx

演示程序

using System;
public class ProfilerSample1
{
    static void Main(string[] args)
    {
        int start = Environment.TickCount;
        for (int i = 0; i < 1000; i++)
        {
            string s = "";
            for (int j = 0; j < 100; j++)
            {
                s += "Outer index = ";
                s += i;
                s += " Inner index = ";
                s += j;
                s += " ";
            }
        }
        Console.WriteLine("Program ran for {0} seconds",
            0.001 * (Environment.TickCount - start));
    }
}
你能想到这个程序在运行期间居然要分配1.6GB的内存吗?
 

image

image

image

查看堆上面分配的情况

image

image

image

image

image

大家可能很惊讶,为什么这么简单的代码居然要用那么多内存空间呢?

其实这也是我们经常所说的,不要在大量的循环中使用字符串(string)拼接,因为string类型在.NET中是一个特殊的引用类型,它本身不可改变。

那么,如果我们将代码稍作一些修改,如下

using System;
using System.Text;

public class ProfilerSample1
{
    static void Main(string[] args)
    {
        int start = Environment.TickCount;

        for (int i = 0; i < 1000; i++)
        {
            StringBuilder sb = new StringBuilder();
            for (int j = 0; j < 100; j++)
            {
                sb.Append("Outer index = ");
                sb.Append(i);
                sb.Append(" Inner index = ");
                sb.Append(j);
                sb.Append(" ");
            }
        }
        Console.WriteLine("Program ran for {0} seconds",
            0.001 * (Environment.TickCount - start));
    }
}

再次运行,我们发现首先运行时间大致只有1.4秒了,原先是5.07秒,大约是4倍的速度差异

image

而且此时程序所分配的内存大致为20MB,原先为1.6GB。

image

并且GC工作的次数也只有10次。大大地降低了CLR的负荷


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值