简体   繁体   中英

How would I use a delegate in this scenario?

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 ForEach method on the List<T> class. The short answer to your question is no .

The equivalent syntax would be:

initialValue.Select(k => k.Key)
            .Concat(credits.Select(k => k.Key))
            .Concat(debits.Select(k => k.Key))
            .Distinct()
            .ToList()
            .ForEach(var => r.Add(key,
                (initialValue.ContainsKey(key) ? initialValue[key] : 0M)
                + (credits.ContainsKey(key) ? credits[key] : 0M)
                - (debits.ContainsKey(key) ? debits[key] : 0M)
                ));

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.

Can anyone offer a way to rewrite this using delegates?

But you are using delegates already! That's what the lambdas are being converted to. The question about whether to use a delegate or not for the loop-body for performance reasons is a little strange when so many delegate invocations are being used just to produce each item of the sequence.

Anyway, Adam Robinson has already covered how you would List.ForEach to execute a side-effect on each item of a list and the associated readability and performance implications, so I won't go into that.

But here's how I would write your method if the marginal overhead of LINQ and delegate invocations were not a deciding factor:

return initialValue
       .Concat(credits)
       .Concat(debits.Select(kvp => new KeyValuePair<string, decimal>(kvp.Key, -kvp.Value)))
       .GroupBy(kvp => kvp.Key, kvp => kvp.Value)
       .ToDictionary(group => group.Key, group => group.Sum());

Now that's much more readable.

The foreach construct is the right one if you want to build a new dictionary using Dictionary.Add . You can always just select from the existing dictionary to create a new one, but that will be slower.

However, as to readability, isn't this much easier?

private static decimal GetOrZero(this IDictionary<string,decimal> dict, string key)
{
    decimal value = 0;
    dict.TryGetValue(key, out value);
    return value;
}

private static IDictionary<string, decimal> CalculateBalances(
    IDictionary<string, decimal> initialValue, 
    IDictionary<string, decimal> credits, 
    IDictionary<string, decimal> debits)
{   
    var r = new Dictionary<string, decimal>();
    var accounts = initialValue.Keys.Union(debits.Keys).Union(credits.Keys);

    foreach (var accounts in accounts)
    {
        r.Add(initialValue.GetOrZero(key) + credits.GetOrZero(key) - debits.GetOrZero(key));
    }

    return r;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM