"Closure over variable gives slightly worse performance". How?
c#
Solution
First of all, those two solutions are not functionally equivalent (If you fix comparing a date with an int (`.Date == .Today.Year`)):
The first snippet re-evaluates `DateTime.Today.Year` for each value of the list, which can give different results when the current year changes during iteration
The second snippet stores the current year and re-uses that, so all items in the resulting list will have the same year. (I'd personally take this approach, as I want to make sure the result is sane).
The closure is introduced because the lambda accesses a variable from its outer scope, it closes over the value of `yr`. The C# compile will generate a new class with a field which holds the `yr`. All references to `yr` will be replaced with the new field and the original `yr` will not even exist in the compiled code
I doubt there will be a performance penalty by introducing a closure. If any, the code using the closure will be faster, since it does not have to create new `DateTime` instances for every list item and then dereference two properties. It only has to access the field of the compiler-generated closure class which holds the int value of the current year. (Anybody who wants to compare the generated IL code or profile the two snippets? :))
Problem
While giving answer to an SO question, I was told that my solution will introduce a closure over variable so it will have slightly worse performance. So my question is: - How will there be a closure? - How will it affect performance? Here is the question ``` List.Where(s => s.ValidDate.Date == DateTime.Today.Year).ToList(); ``` Here is my solution. I introduced the variable `yr` to store year. ``` int yr = DateTime.Now.Year; List.Where(s => s.ValidDate.Year == yr).ToList(); ``` Here it is in the answer's comments