這篇博文給大家分享的是,如何使用VS自帶的性能分析工具來分析我們編寫的.NET程序,一邊找出程序性能的瓶頸,改善代碼的質(zhì)量。在實(shí)際開發(fā)中,性能真的很重要,往往決定一個(gè)產(chǎn)品的生死~良好的用戶體驗(yàn)的基礎(chǔ)之一也是程序要有好的性能~
下面以一個(gè)大家熟悉比較極端的例子,來說明編寫代碼時(shí)考慮性能的重要性。這里DebugLZQ用的是10.0版本的VS。
示例程序代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace VS2010性能測試
{
class Program
{
static void Main(string[] args)
{
int start = Environment.TickCount;
for (int i = 0; i < 1000; i++)
{
string s = "";
for (int j = 0; j <200; j++)
{
s += "Outer index = ";
s += i;
s += " Inner index = ";
s += j;
s += " ";
}
}
int middle = Environment.TickCount;
Console.WriteLine("Program part1 run for {0} seconds",0.001 * (middle - start));
//
for (int i = 0; i < 1000; i++)
{
StringBuilder s = new StringBuilder();
for (int j = 0; j <200; j++)
{
s.Append("Outer index = ");
s.Append(i);
s.Append("Inner index = ");
s.Append(j);
s.Append(" ");
}
}
int end = Environment.TickCount;
Console.WriteLine("Program part2 run for {0} seconds", 0.001 * (end - middle));
//
Console.ReadKey();
}
}
}
差距就是這么大!
我們可以使用VS自帶的性能分析工具來分析這個(gè)程序?梢酝ㄟ^“分析”--“啟動性能向?qū)А眮韱有阅芊治?/p>
我們可以根據(jù)需要選擇不同的分析方法
面以“CPU采樣”分析為例
切換到函數(shù)視圖
定位到我們的源碼:
問題找到了~