Suppose I have the following code:
var X = XElement.Parse (@"
<ROOT>
<MUL v='2' />
<MUL v='3' />
</ROOT>
");
Enumerable.Range (1, 100)
.Select (s => X.Elements ()
.Select (t => Int32.Parse (t.Attribute ("v").Value))
.Aggregate (s, (t, u) => t * u)
)
.ToList ()
.ForEach (s => Console.WriteLine (s));
What is the .NET runtime actually doing here? Is it parsing and converting the attributes to integers each of the 100 times, or is it smart enough to figure out that it should cache the parsed values and not repeat the computation for each element in the range?
Moreover, how would I go about figuring out something like this myself?
Thanks in advance for your help.
It has been a while since I dug through this code but, IIRC, the way
Selectworks is to simply cache theFuncyou supply it and run it on the source collection one at a time. So, for each element in the outer range, it will run the innerSelect/Aggregatesequence as if it were the first time. There isn’t any built-in caching going on — you would have to implement that yourself in the expressions.If you wanted to figure this out yourself, you’ve got three basic options:
ildasmto view the IL; it’s the most accurate but, especially with lambdas and closures, what you get from IL may look nothing like what you put into the C# compiler.