tags:

views:

615

answers:

2
    Dim myString As String = "1234567890"
    Dim Part As String = ""

    Part = myString.Substring(2, 2) '34
    Part = New String(myString.Skip(2).Take(2).ToArray) '34

This code work but the linq one take about 1300% more time than the substring.

I have 2 questions

  1. Do I have the correct syntax(for LINQ)?
  2. Should I stick with the string.substring?
+4  A: 

You should definitely stick with Substring. It's tailor-made for this situation, and it doesn't require all the extra bits of LINQ.

Just because you can do something with LINQ doesn't mean it's necessarily a good idea. When the data type you're using has the exact operation you want defined on it already, using an extra layer of abstraction is somewhat pointless.

Jon Skeet
Wait, what? I thought LINQ was the answer to every question... :)
Jonathan
A: 

1) Yes, that is one way of doing it. I'm sure there are others.
2) Yes. Definitely.

Linq takes longer because it is doing a lot more. It has to create an expression tree, evaluate the expression an iterator, which calls the strings enumerator to move along the string the required number of characters, then do it all again for your second method call, then convert the whole lot to an array, then create a new string and process the array into the new string.

All the substring call has to do is a bit of pointer arithmetic to extract the middle portion of the string and return the new string.

This is a perfect example of an absolutely terrible use for Linq. Linq is for helping the developer with complex queries on enumerable or query-able data, not processing strings. Here the overhead of Linq by far outweighs any benefits in readability. Stick with the substring call.

[Edit: Corrected linq details following comments from Marc]

Simon P Stevens
LINQ-to-Objects doesn't use expression trees - it compiles directly to anonymous methods. But yes, there is no need to use LINQ here ;-p
Marc Gravell
@Marc: Very true. I made an assumption based on Linq-to-sql. Checked it out in reflector and it does just do a bunch of stuff with iterators and enumerators. Corrected the answer to match.
Simon P Stevens