I wrote two simple applications:
1. one using anonymous methods, and
2. one using simple methods.
Each of the methods above are doing a simple action:
int add(int n1, int n2) {return n1+n2}
And I call a simple for loop that will call the add method 10,000 times. The implementation using anonymous methods takes much less time than the other. Why? Is it because the JITter inlines anonymous methods?
delegate int ADD( int i1, int i2 );
private void button1_Click( object sender, EventArgs e )
{
Stopwatch watch = new Stopwatch();
watch.Reset();
watch.Start();
for( int i = 0 ; i < 10000 ; i++ )
{
add( i, i );
}
watch.Stop();
Console.WriteLine("Normal Call " + watch.ElapsedTicks);
watch.Reset();
watch.Start();
for( int i = 0 ; i < 10000 ; i++ )
{
ADD p = delegate( int n1, int n2 )
{
return n1 + n2;
};
p.Invoke( i, i );
}
watch.Stop();
Console.WriteLine( watch.ElapsedTicks );
Console.ReadLine();
}
int add(int n1, int n2)
{
return n1 + n2;
}
}
The result – on release mode – compile on x64 ( pressed on the action button couple of times ):
Normal 1525
1275
Normal 480
477
Normal 371
370
Normal 372
371
Normal 477
479
Normal 477
477
Normal 564
702
Normal 478
476
I could not confirm your results.
In my testing, the “normal” function performs about order of magnitude better than the delegate. Here is your slightly modified code that I used for testing:
This prints:
You must be doing something that skews the results.
— EDIT —
OK I’ve done another round of testing, this time with a WinForms application.
static, it speeds-up again (in ‘x64’ WinForms build).Everything was measured outside debugger in Release configuration.