Reputation: 21280
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.
Upvotes: 1
Views: 108
Reputation: 46005
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)
Upvotes: 2
Reputation: 1534
To call orignal.ToLower()
only once won't change anything real in performance.
Try to use e.g. Parallel LINQ to get the result faster if you got enough CPU-Power left.
Upvotes: 0
Reputation: 3752
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(){...}
Upvotes: -2
Reputation: 12859
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.
Upvotes: 0
Reputation: 4654
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();
Upvotes: 0
Reputation: 101742
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();
Upvotes: 5