开发者

How much less efficent would the linq technique be in the following case and could either be optimised?

开发者 https://www.devze.com 2023-02-28 15:35 出处:网络
How much less efficent would the linq technique be in the following case and could 开发者_运维知识库either be optimised?

How much less efficent would the linq technique be in the following case and could 开发者_运维知识库either be optimised?

Linq technique:

public String FindProviderName(Int32? TrueName)
{
    String providerName = (from p in this.Providers
                           where p.TrueName == TrueName
                           select p.ProviderName).First().ToString();

    return providerName;
}

Walking technique:

public String FindProviderName(Int32? TrueName)
{
    String providerName = String.Empty;

    foreach (IProvider provider in this.Providers)
    {
        if (provider.TrueName == TrueName)
        {
            providerName = provider.ProviderName;
            break;
        }
    }

    return providerName;
}


If that is LINQ-to-objects, they'll both be pretty fast. If you want faster, consider a Dictionary<int,string> and use TryGetValue(...). Obviously you need to pre-generate the dictionary, perhaps via ToDictionary().

Note that the two examples shown are different when there is no match; one throws; one returns an empty string. Also, there is no need to call ToString() on a string.


Re the faster version (comments); you need a field,

Dictionary<int,string> lookup;

And at some point prior to use (or after data changes) you need to populate it:

lookup = providers.Where(p => p.RealName != null)
    .ToDictionary(p => p.RealName.Value,
        p => p.ProviderName);

Then your lookup would be like:

string providerName;
if(realName == null ||
    !lookup.TryGetValue(realName.Value, out providerName))
    return null;
return providerName;


You have the code, if you want to know how efficient it is, just measure it.

Of course, people quite often worry about efficiency of code, when they shouldn't. Isn't readability more important? Is this the code that slows you down?

That being said, the firs code could be made slightly faster like this:

public String FindProviderName(Int32? TrueName)
{
    String providerName = this.Providers
                              .First(p => p.TrueName == TrueName)
                              .Select p.ProviderName);

    return providerName;
}

And the second one may be made faster by using for instead of foreach (if your collection type is List<T> or an array.

Both those optimizations most likely won't have any measurable effect, though.

0

精彩评论

暂无评论...
验证码 换一张
取 消