First of all Microsoft Performance Explorer must not be used to measure execution times or performance comprasion.
I wanted to check the boxing and unboxing performance and tried to use Microsoft Performance Explorer result it sucks try it,you can’t trust its execution times.So i used this code
1: public static class PerformanceTimer
2: {
3: [DllImport("Kernel32.dll")]
4: public static extern void QueryPerformanceCounter(ref long ticks);
5:
6: static long startTime = 0;
7: static long stopTime = 0;
8:
9: public static void Start()
10: {
11: QueryPerformanceCounter(ref startTime);
12: }
13:
14: public static void Stop()
15: {
16: QueryPerformanceCounter(ref stopTime);
17: }
18:
19: public static long Time
20: {
21: get
22: {
23: return stopTime - startTime;
24: }
25: }
26: }
and got real results,
1-Never use microsoft performance explorer
2-Don’t use boxing it is really 20 times slower
here are my execution times
1636417 ticks used boxing
82530 ticks did not use boxing
1: class Program
2: {
3:
4: static void Main(string[] args)
5: {
6: Stopwatch sw = new Stopwatch();
7: sw.Start();
8: PerformanceTimer.Start();
9: //ArrayList aList = new ArrayList(1000001);
10: //aList.Add(0);
11: //for (int i = 0; i < 999999; i++)
12: //{
13: // aList.Add(i);
14: // int a = Convert.ToInt32(aList[i]) + 2;
15: // aList[i] = a;
16: //}
17: List<int> gList = new List<int>(999999);
18: for (int i = 0; i < 999999; i++)
19: {
20: gList.Add(i);
21: int a = gList[i] + 2;
22: gList[i] = a;
23: }
24: PerformanceTimer.Stop();
25: sw.Stop();
26: double ms = (sw.ElapsedTicks * 1000.0) / Stopwatch.Frequency;
27: Console.WriteLine(PerformanceTimer.Time.ToString());
28: Console.WriteLine(sw.ElapsedMilliseconds.ToString());
29: Console.WriteLine(ms.ToString());
30: Console.Read();
31: }
32: }
used upper code to test performances, used arraylist as boxing example and used generic list as non boxing.
U can also use System.Diagnostics.Stopwatch;
3- Use Convert to it is better than implicit cast.
4-Use String builder instead of + to build large strings.
5-Use String.Equals instead of == and String.IsNullorEmpty instead of !=.
6-I tested for vs foreach i think there is no difference in execution times.(tested summing an array of 10000 random number previously generated).
No comments:
Post a Comment