zoukankan      html  css  js  c++  java
  • .NET : CLR Profiler的使用

    经常讲课的时候会提到值类型和引用类型,也会提到如何查看它们的大小。多次被朋友问到,如何真的想要知道到底每个方法分配了多少内存之类的问题,其实这可以通过CLR Profiler工具来监控。

    有兴趣的朋友可以查看下面这篇文档

    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的负荷

  • 相关阅读:
    什么时候用resultMap,什么时候用resultType?
    Cannot create PoolableConnectionFactory解决思路
    去除list集合中重复项的几种方法-转载
    ORA-02298 定位问题
    命令行退出MySQL和登录MySQL
    CX4-480服务器数据恢复过程(服务器数据恢复通用方法)
    也谈腾讯云的静默损坏
    raid5阵列两块硬盘离线怎么解决
    服务器卷删除初检报告/数据恢复成功率分析
    服务器两块硬盘离线如何恢复数据
  • 原文地址:https://www.cnblogs.com/chenxizhang/p/1623071.html
Copyright © 2011-2022 走看看