상식적으로 봤을 때…
인스턴스 메서드를 호출하는 델리게이트 vs 정적 메서드를 호출하는 델리게이트
둘이 대결하면 후자가 빠르지 않겠습니까?
(인스턴스는 활용하지 않는다고 가정)
그래서 다음과 같이 테스트를 해봤습니다.
MyDelegate.cs
namespace MyDelegate
{
delegate void MyCallback(int[] ints, int i);
internal class MyDelegate
{
static public MyDelegate myDelegate = new MyDelegate();
static public MyCallback myCallback = null;
static public MyCallback myStaticCallback = Test;
public int testMember;
public static void Test(int[] ints, int i)
{
if (i < ints.Length)
{
ints[i] = i;
}
}
public void Test2(int[] ints, int i)
{
if (i < ints.Length)
{
ints[i] = i;
}
}
public static void Init()
{
myCallback = myDelegate.Test2;
}
}
}
테스트를 시행한 코드(Program.cs)
MyDelegate.MyDelegate.Init();
Random random = new Random();
const int repeat = 15000;
int[] array1 = new int[repeat];
int[] array3 = new int[repeat];
var a = CostTester.Test(() =>
{
for (int j = 0; j < repeat; j++)
{
for (int i = 0; i < repeat; i++)
{
MyDelegate.MyDelegate.myCallback(array1, i);
}
}
});
var c = CostTester.Test(() =>
{
for (int j = 0; j < repeat; j++)
{
for (int i = 0; i < repeat; i++)
{
MyDelegate.MyDelegate.myStaticCallback(array3, i);
}
}
});
Console.WriteLine("인스턴스메서드 델리게이트: " + "테스트값:" + array1[random.Next(array1.Length)] + ", 소요 시간:" + a.ms
+"\n정적 메서드 델리게이트: " + "테스트값:" + array3[random.Next(array3.Length)] + ", 소요 시간:" + c.ms);
CostTester.cs
namespace MyDelegate
{
internal class CostTester
{
public delegate void TestFunction();
static Stopwatch sw = new Stopwatch();
public static (long ms, long ticks) Test(TestFunction testFunction)
{
sw.Restart();
testFunction();
sw.Stop();
return (sw.ElapsedMilliseconds, sw.ElapsedTicks);
}
}
}
테스트 결과는 항상 근소하게 인스턴스 메서드 쪽이 이깁니다.
정적 메서드가 인자도 하나 덜 전달해도 되고… 더 나을 거라 생각했는데…
도대체 왜 그런 걸까요…?