views:

105

answers:

1

Are there any disadvantages or performance slowdowns related to the use of expressions like

from i in Enumerable.Range(1, Math.Min(strTexto.Length, tamMax) + 1)
                select Tuple.Create(strTexto.Substring(0, i - 1), strTexto.Substring(i - 1))

in C#? Is it preferable to build "hard-coded queries" like

foreach (Int32 IntTmp in SomeListWithTheRange)
    SomeListWithTheTuples.Add(new Tuple<String, String> (strTexto.Substring(0, i - 1), strTexto.Substring(i - 1)))

?

While the first one seems more readable at first glance, I have noticed that this kind of queries can get very slow... For instance, the first query takes 11ms to perform, while the second one takes only 1ms. Am I right? Just want to make sure since I need to implement lots of these kind of queries.

+3  A: 

The first approach will perform just as well as the second. When you say that you "have noticed that this kind of queries can get very slow" - could you provide more details? You can certainly write slow LINQ queries, but that's a matter of using LINQ appropriately.

Note that your two code samples aren't equivalent at the moment at all - the first just builds a query, but doesn't use it at all. Your second seems to be calling Concat repeatedly, which will be slow when you iterate over it, as you'll end up with an awful lot of iterators.

If you could explain what you're actually trying to do, that would help a lot.

Jon Skeet
In the method where I am using this query, I have the ''return'' keyword just before the query so that it will return the results in an enumerable fashion. There's however another function, where I use ''Concat'' four times, each of which has a query of the kind inside it. Can that make things slower?
Miguel
@Miguel: Again, you'd have to give more details. It's very hard to talk about performance based on sketchy details. Calling Concat 4 times probably won't be too bad, but you *will* have 4 levels of indirection.
Jon Skeet