I can't express my thoughts systematically. I will test them first to see if there are any problems.
Commissioned test: Public delegate T Func1 <T, T1> (T1 t );
Public class FuncTest {
Public readonly Func1 <long, long> Test;
Public FuncTest (){
Test = Fib;
}
Private long Fib (long n ){
If (n <= 1 ){
Return n;
}
Else {
Return Test (n-1) + Test (n-2 );
}
}
}
Delegation of property packaging: Public class FuncInAGetterTest {
Private readonly Func1 <long, long> _ Test;
Public FuncInAGetterTest (){
_ Test = Fib;
}
Public Func1 <long, long> Test {
Get {
Return _ Test;
}
}
Private long Fib (long n ){
If (n <= 1 ){
Return n;
}
Else {
Return Test (n-1) + Test (n-2 );
}
}
}
Class test: Public class ClassTest {
Public long Test (long n ){
If (n <= 1 ){
Return n;
}
Else {
Return Test (n-1) + Test (n-2 );
}
}
}
Interface Test: Public interface IInterfaceTest {
Long Test (long n );
}
Public class InterfaceTest: IInterfaceTest {
Private IInterfaceTest _ interface;
Public InterfaceTest (){
_ Interface = this;
}
Private long Test (long n ){
If (n <= 1 ){
Return n;
}
Else {
Return _ interface. Test (n-1) + _ interface. Test (n-2 );
}
}
# Region IInterfaceTest Members
Long IInterfaceTest. Test (long n ){
Return Test (n );
}
# Endregion
}
Test code: [TestMethod]
Public void ClassInterfaceDelegatePerformance (){
//
// TODO: Add test logic here
//
Stopwatch sw = new Stopwatch ();
ClassTest classTest = new ClassTest ();
IInterfaceTest interfaceTest = new InterfaceTest ();
FuncTest funcTest = new FuncTest ();
FuncInAGetterTest funcInAGetter = new FuncInAGetterTest ();
Long classResult = 0;
Sw. Start ();
For (int I = 0; I <20; I ++)
ClassResult = classTest. Test (30 );
Sw. Stop ();
Long classTime = sw. ElapsedMilliseconds;
Sw. Reset ();
Sw. Start ();
For (int I = 0; I <20; I ++)
InterfaceTest. Test (30 );
Sw. Stop ();
Long interfaceTime = sw. ElapsedMilliseconds;
Long funcResult = 0;
Sw. Reset ();
Sw. Start ();
For (int I = 0; I <20; I ++ ){
FuncResult = funcTest. Test (30 );
}
Sw. Stop ();
Long funcTime = sw. ElapsedMilliseconds;
Sw. Reset ();
Sw. Start ();
For (int I = 0; I <20; I ++)
FuncInAGetter. Test (30 );
Sw. Stop ();
Debug. WriteLine ("Class:" + classTime. ToString () + ", Interface:" + interfaceTime. ToString () +
", Func:" + funcTime. ToString () + ", Func In a Getter:" + sw. ElapsedMilliseconds. ToString ());
Assert. IsTrue (classTime> funcTime, "Func is slower! ");
Assert. AreEqual (classResult, funcResult, "Not Equal! ");
}
}
Result:
Class: 1050, Interface: 1802, Func: 1008, Func In a Getter: 1525