I was curious to see what the performance differences between returning a value from a method, or returning it through an Action parameter.
There is a somewhat related question to this http://stackoverflow.com/questions/2082735/performance-of-calling-delegates-vs-methods
But for the life of me I can't explain why returning a value would be ~30% slower than calling a delegate to return the value. Is the .net Jitter (not compiler..) in-lining my simple delegate (I didn't think it did that)?
class Program
{
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
sw.Start();
A aa = new A();
long l = 0;
for( int i = 0; i < 100000000; i++ )
{
aa.DoSomething( i - 1, i, r => l += r );
}
sw.Stop();
Trace.WriteLine( sw.ElapsedMilliseconds + " : " + l );
sw.Reset();
sw.Start();
l = 0;
for( int i = 0; i < 100000000; i++ )
{
l += aa.DoSomething2( i - 1, i );
}
sw.Stop();
Trace.WriteLine( sw.ElapsedMilliseconds + " : " + l );
}
}
class A
{
private B bb = new B();
public void DoSomething( int a, int b, Action<long> result )
{
bb.Add( a,b, result );
}
public long DoSomething2( int a, int b )
{
return bb.Add2( a,b );
}
}
class B
{
public void Add( int a, int b, Action<long> result )
{
result( a + b );
}
public long Add2( int i, int i1 )
{
return i + i1;
}
}