3 ms·
In C#/.Net there's language constructs like LINQ, and framework methods on generic collections like Select() and Where() and SkipWhile(), etc. For example, if
by henrikschroder 7y ago
In C#/.Net there's language constructs like LINQ, and framework methods on generic collections like Select() and Where() and SkipWhile(), etc.
For example, if you want to write code that returns the first X items in an array that satisfy a predicate P, it will look a lot neater and readable using code like that, than if you were to write it with for loops and if statements.
But it's still just syntactic sugar, the neater code just masks the underlying code that contains the actual loops and conditionals.
As always, it's a tool, and can be misused like all tools. It's a balance, the neater code might be more readable, but the for/if code might be easier to change or optimize down the line if conditions change. It all depends. There are no silver bullets, just tools, and trying to minimize the amount of tools in your toolbox is just dumb.
- Gibbon1 7y ago> But it's still just syntactic sugar, the neater code just masks the underlying code that contains the actual loops and conditionals. It seemed to me that was often more performant than using a loop.
- wffurr 7y agoLinq pipelines are lazily evaluated, so you can get linear performance instead of polynomial.
- henrikschroder 7y agoIt depends on what you do, and the underlying code can be pretty smart. But it can also be pretty dumb. The main difference is that if you use .Where(P).Take(X), you're actually generating a new enumerator, a new coroutine, and that code doesn't get called until you actually enumerate it. But if you write your for/if loop, you run the code immediately, you go through the source array, run the predicate on each item, until you have your X items, and then you return a new array with those elements.