But what about performance?
Running the code below (LinqPad) resulted in
1,000,000,000 Native operations: 358,930,064 ticks
1,000,000,000 Dynamic operations: 369,853,643 ticks
Since there are 10,000 ticks in a millisecond this works out at:
1,000,000,000 Native operations: 35,893 ms
1,000,000,000 Dynamic operations: 36,985 ms
var stopwatch = new Stopwatch();
var iterations = 1_000_000_000;
var rng = new Random();
var greaterThan = 0;
stopwatch.Start();
for (var iteration = 0; iteration < iterations; iteration++){
var (a, b) = (rng.Next(), rng.Next());
if (a > b) {
greaterThan++;
}
}
stopwatch.Stop();
Console.WriteLine($"{iterations:0,000} Native operations: {stopwatch.ElapsedTicks:0,000} ticks");
Expression<Func<int, int, bool>> GreaterThan = (a, b) => a > b;
var compiled = GreaterThan.Compile();
greaterThan = 0;
stopwatch.Reset();
stopwatch.Start();
for (var iteration = 0; iteration < iterations; iteration++)
{
var (a, b) = (rng.Next(), rng.Next());
if (compiled(a,b))
{
greaterThan++;
}
}
stopwatch.Stop();
Console.WriteLine($"{iterations:0,000} Dynamic operations: {stopwatch.ElapsedTicks:0,000} ticks");
Doing the same but using a lambda (Func<int, int, bool>
) yielded very similar results:
1,000,000,000 Native operations: 354,127,563 ticks
1,000,000,000 Dynamic operations: 401,450,782 ticks
Or:
1,000,000,000 Native operations: 35,412 ms
1,000,000,000 Dynamic operations: 40,145 ms
Making it faster
The easy way to make the above code faster would be to remove the random number generation from within the loop. Just using 2 random numbers generated before either of the timed sections greatly reduces the the run time, to about 3.1 seconds (Native) and 7.9 seconds (Dynamic).
Conclusion
So, while it does seem to take about twice as long to use a dynamic operation instead of the native operation, the overall performance impact will likely be swamped by the rest of the code within the loop. In short, don't worry about it until it does actually become an issue.
Final thoughts
It is likely that there is a way to improve the performance of the dynamic check but doing so will likely reduce the maintainability of the code.
Disclaimer: The times seen here are very subjective and will depend upon the spec of the computer running the code