Please, it is just a ‘var’
OK, on a previous post I had a little bit of code with a ?var? statement in it. Actually, there were a few other items in there, couple of lambdas, lots of nested ?if?s, etc. There was a lot of good hand wrangling on how performant the Lambda ?Where? function is. According to the comments, not very performant for very large datasets. I don?t have a problem with that.
But at some point one of the commentors noticed that the var statement was just as fast as the explicitly called out type. Let me spell something out real quick: Once compiled, there is no difference between var and explicit types. ?var? is a language sort-cut, asking the compiler to figure out the type and inject it. This is not a runtime feature ? ?var? is a compile time feature.
Now, how often do I use var in my code? All the time. I use it practically everywhere. Think of it as a refactoring helper. Sometime I have to change a method from returning a IList to an IEnumerable. If I use a var and a foreach then none of the rest of my code has to change. That, to me is flexible code.
I could make my code more performant by replacing the foreach loops with for loops ? but I?ll keep the var?s thank-you-very-much. But most of the time I am not dealing with enough data to make that worth it. Most of the time I?m working with data to get displayed on web and mobile user interfaces. In those cases, limiting the amount of data I need to process, and then display, is of upmost importance. If I?m doing a file import (rare, but it does happen), then I switch to the other techniques.
Now, why bother? Why not always use the fastest method all the time? Because I find the foreach with ?var?s easier to read, more flexable code, and more refactoring friendly. For the vast majority of my code, that matters a lot more than eking out every last bit of performance.