自從 C# 3.0 (VS2008) 引入 anonymous method, 我很愛用這個, 但是記得曾經看過 delegate performance 不如 virtual function 好,
所以寫個小程式試驗.
在知道結果之後, 有找到官方說法:
The Truth about Delegates
其中有提到 : "Delegates are efficient. Invoking a delegate is as fast as invoking a virtual method."
那就看看程式執行結果吧:
Code:
1: using System;2: using System.Collections.Generic;3: using System.Text;4:
5: namespace DelegatePerformance6: {
7: class Program8: {
9: static void Main(string[] args)10: {
11: for (int i = 0; i < 5; i++)12: {
13: int testtimes = 100000000;14: test1 t1 = new test1(delegate() { return 0; });15: test2 t2 = new test2();16: test1 t3 = new test1(new test1.SimpleDelegate(f1));17: test1 t4 = new test1(new test1.SimpleDelegate(new Program().f2));18: DateTime begin1 = DateTime.Now;
19: t1.dofunction(testtimes);
20: DateTime end1 = DateTime.Now;
21: DateTime begin2 = DateTime.Now;
22: t2.dofunction(testtimes);
23: DateTime end2 = DateTime.Now;
24: DateTime begin3 = DateTime.Now;
25: t3.dofunction(testtimes);
26: DateTime end3 = DateTime.Now;
27: DateTime begin4 = DateTime.Now;
28: t4.dofunction(testtimes);
29: DateTime end4 = DateTime.Now;
30: Console.WriteLine("delegate:" + (end1 - begin1).ToString() + " , without delegate:" + (end2 - begin2).ToString() + " , delegate2:" + (end3 - begin3).ToString() + " , delegate3:" + (end4 - begin4).ToString());31: }
32: }
33: static int f1()34: {
35: return 0;36: }
37: int f2()38: {
39: return 0;40: }
41: }
42:
43: class test144: {
45: public delegate int SimpleDelegate();46:
47: private SimpleDelegate msd;48: public test1(SimpleDelegate sd)49: {
50: msd = sd;
51: }
52:
53: public void dofunction(int times)54: {
55: for (int i = 0; i < times; i++)56: msd();
57: }
58: }
59:
60: class test261: {
62: private int ssd()63: {
64: return 0;65: }
66:
67: public test2()68: {
69: }
70:
71: public void dofunction(int times)72: {
73: for (int i = 0; i < times; i++)74: ssd();
75: }
76: }
77: }
執行結果:
delegate:00:00:00.9740000 , without delegate:00:00:00.7070000 , delegate2:00:00:01.0150000 , delegate3:00:00:00.8260000
delegate:00:00:00.9470000 , without delegate:00:00:00.6970000 , delegate2:00:00:01.0150000 , delegate3:00:00:00.8230000
delegate:00:00:00.9500000 , without delegate:00:00:00.6930000 , delegate2:00:00:01.0110000 , delegate3:00:00:00.8260000
delegate:00:00:00.9500000 , without delegate:00:00:00.7030000 , delegate2:00:00:01.0110000 , delegate3:00:00:00.8240000
delegate:00:00:00.9530000 , without delegate:00:00:00.6950000 , delegate2:00:00:01.0190000 , delegate3:00:00:00.8350000
看樣子差不了多少...雖然有慢一點點, 不過以一億次 times 的scale 應該還好.
...Read more.