简体   繁体   中英

How I can Optimize this linq query

Is there some way to optimize this query ?

_alternatives.Cast<AlternativePartName>()
                                .Where(alt => original.ToLower() == alt.CompName)
                                .Select(alt => alt.AltCompName).ToList();

I am profiling my application and this code is one of the bottlenecks 196 ms but it executed a lot of times.

Instead of calling ToLower for each item, call it only once:

var lower = original.ToLower();

_alternatives.Cast<AlternativePartName>()
              .Where(alt =>  lower == alt.CompName)
              .Select(alt => alt.AltCompName).ToList();

You should try to use more of your cores with .AsParallel() - this could be a improvement at huge lists with long strings

string lower = original.ToLower();
_alternatives.Cast<AlternativePartName>()
              .AsParallel()
              .Where(alt =>  lower == alt.CompName)
              .Select(alt => alt.AltCompName)

I'm assuming that "original" and "CompName" are strings. If yes, then you should do the following:

_alternatives.Cast<AlternativePartName>()
                                .Where(alt => String.Equals(original, alt.CompName, StringComparison.OrdinalIgnoreCase))
                                .Select(alt => alt.AltCompName).ToList();

Using correct data structures is best way to increse performance. In your case, it would be better if you used dictionary with CompName being the key and list of AltCompNames being the item. The lookup would be blazing fast, because there would be no iteration, just single lookup. And keeping such simple structure up-to-date with adding and removing items should not be a huge problem.

To call orignal.ToLower() only once won't change anything real in performance.

Try to use eg Parallel LINQ to get the result faster if you got enough CPU-Power left.

I am not so good with the dot syntax, but this

.Select(alt => alt.AltCompName)

combined with this

_alternatives.Cast<AlternativePartName>()

Could be achived with the select directly making the AlternativPartName

select new AlternativePartName(){...}

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