In depth analysis of c sharp interface versus delegate performance comparisons
- 2020-04-02 01:04:50
- OfStack
preface
I saw it in Code Complete 2nd before
Instead of using a delegate in a language like C#, try not to use a delegate. Instead, use interfaces to avoid the impact on performance
Truth comes from practice, so I wrote a little sample to test it
My hardware is 2.66 gb 4 core CPU and 4 gb of memory
I saw it in Code Complete 2nd before
Instead of using a delegate in a language like C#, try not to use a delegate. Instead, use interfaces to avoid the impact on performance
Truth comes from practice, so I wrote a little sample to test it
My hardware is 2.66 gb 4 core CPU and 4 gb of memory
< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201305/2013053110485913.jpg ">
I don't know if the computer is faster and the function I wrote is too small
It took 10 million to see an impact
< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201305/2013053110485914.jpg ">
It looks fine after 100 million
Overall and analysis, or will have an impact
If you need to be efficient or embedded, you should be a little bit more careful
code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace Performance
{
class Program
{
delegate int Add(int a, int b);
static Add myDelegate;
const int LOOP_COUNT = 100000000;
static void Main(string[] args)
{
myDelegate = new Add(TestAdd);
IOrz orz = new Orz();
Stopwatch st = new Stopwatch();
st.Start();
for (int i = 0; i < LOOP_COUNT; i++)
{
int c = orz.DoIt(1, 2);
}
st.Stop();
Console.WriteLine(" Call Interface Elapsed time:{0} ms", st.ElapsedMilliseconds);
st.Reset();
st.Start();
for (int i = 0; i < LOOP_COUNT; i++)
{
int d = myDelegate(3, 5);
}
st.Stop();
Console.WriteLine("Call Delegate Elapsed time :{0} ms", st.ElapsedMilliseconds);
Console.ReadLine();
}
static int TestAdd(int a, int b)
{
int c = a + b;
return c;
}
}
}