I have a need to optimize a large apps that use linq extensively. Many of the linq statements create anonymous objects within the linq extension methods. An example :-
// custom sort order
var sortedData = data.OrderBy(x => (new List<string>() {"Orange", "Apple", "Pear" }).IndexOf(x.Name));
foreach (var d in sortedData) {
....
The problem is that a new List gets created for every iteration.
Is there a compiler flag I can set to get the compiler to do some static analysis and extract the loop invariant code to be outside of the loop?
I think many people got caught up in your order by example and missed your real question.
No there is no simple tool built in to visual studio that can do this statically (without running the program). There are two tools that may help you out if you can run the program and execute the code in question (you do have unit tests that has 100% code coverage don't you ;) ). One is a profiler built in to Visual Studio, and one the other is the CLR profiler.
I have never used the CLR profiler and it may just be a older version of what is in visual studio. The visual studio profiler can show you if a large number of objects are being created (Lists in your example) and see where in the code those objects are being created. It can also show you which lines of code are taking the longest to execute so you know where to focus your effort to speed up your program.
If you have specific issues running the profiler I recommend opening a new question up on the issue,
Why can't you just pull it out yourself?
var fruits = new [] {"Orange", "Apple", "Pear" };
var sortedData = data.OrderBy(x => fruits.IndexOf(x.Name));
foreach (var d in sortedData) {
In addition, if these loops are all in the same class, make fruits
a static readonly
member of the class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With