A developer friend of mine tells me that loops are much faster using delegates, and I’d like to benchmark it, but I’m having trouble connecting the dots on how it works.
Consider the following balance calculator. This basically takes a list of accounts and adds the initial value (starting balance) if it exists to the total credits value if it exist and subtracts the total debits value for each account:
private static IDictionary<string, decimal> CalculateBalances(
IDictionary<string, decimal> initialValue,
IDictionary<string, decimal> credits,
IDictionary<string, decimal> debits)
{
var r = new Dictionary<string, decimal>();
foreach (var key in initialValue.Select(k => k.Key)
.Concat(credits.Select(k => k.Key))
.Concat(debits.Select(k => k.Key))
.Distinct())
{
r.Add(key,
(initialValue.ContainsKey(key) ? initialValue[key] : 0M)
+ (credits.ContainsKey(key) ? credits[key] : 0M)
- (debits.ContainsKey(key) ? debits[key] : 0M)
);
}
return r;
}
This is fairly performant on small to medium account lists, but would using delegates be faster? And frankly, delegate logic seems to be operating at right angles to my thought processes, because I’m scratching my head how to even write this.
Can anyone offer a way to rewrite this using delegates?
I’m assuming your friend is referring to something like the
ForEachmethod on theList<T>class. The short answer to your question is no.The equivalent syntax would be:
This is in no way better than the way you have it above. It is both slower and more difficult to read. Delegate invocation is slower than ordinary method invocation. The syntax you have above is both faster and easier to read.