When testing the relative performance of different method implementations I find myself re-writing functions similar to this.
private static long Measure(
int iterations,
Func<string, string> func,
string someParameter)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
for (var i = 0; i < iterations; i++)
{
func(someParameter);
}
stopwatch.Stop();
return stopwatch.ElapsedTicks;
}
Rather than rewriting this function for every method singnature that I test, would it be possible to write a generic implementation for performance testing any delagate? Something along the lines of
private static long Measure(
int iterations,
Delegate func,
params object[] parameters)
{
...
}
or
private static long Measure<TDelegate>(
int iterations,
TDelegate func,
params object[] parameters)
{
if (!typeof(TDelegate).IsSubclassOf(typeof(Delegate)))
{
throw new ArgumentException("Not a delegate", "func");
}
...
}
If I can do this would it make sense to Compile
an Expression<TDelegate>
before performing the iterations?
Why not use an Action and you can set the parameters in a lambda.
Then you call it like
You can just use an anonymous function to pass the parameters: