One development friend of mine tells me that loops are much faster using delegates, and I would like to compare them, but I am having problems connecting dots to how this works.
Consider the following balance calculator. This basically takes a list of accounts and adds an initial value (initial balance) if it exists for the total value of loans, if it exists, and subtracts the total value of debits 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 pretty efficient with small to medium account lists, but will using delegates be faster? And frankly, delegate logic seems to work at right angles to my thought processes, because I scratch my head, how to even write this.
- ?