C# performance of StringBuilder ToString vs String Substring
===

What is faster having a String and then calling Substring for this String where the first Substring will be the initial String and every new Substring a smaller portion from within the initial substring until its end? Or using a StringBuilder and cutting off more and more from the beginning and then always using ToString from the shrinking string?

This [link][1] describes that the StringBuilder ToString method only allocates new space if a new thread accesses the StringBuilder or the returned String is much smaller than the currently allocated space. This sounds faster than using Substring. I can see this logic within the [implementation][2] up to .Net Framework 3.5. With version 4.0 there is an immediate call to FastAllocateString (more or less like with String Substring). Is it the same logic as in previous framework versions, only hidden now?

Why I need it:

I want to check if the start of an input string matches a regex. As soon as the start is matched an index is set right after the matched substring and the part beginning with the index should now be matched with a regex. Since this is done multiple times the performance should be as good as possible.

In order to avoid searching the whole (remaining) string, I would use the start-anchor (^), so the search can be abborted as soon as possible (after knowing that the start does not match). If I do this I have the problem that I cannot use the start index parameter of the Match method with anything other than 0. Otherwise there would never be a match thanks to the anchor.

So I think I have two possibilities now:

1) Always using the Substring method on the input string and keeping and index for the current position.

2) Using a StringBuilder and always removing the start of the input when matched successfuly. Then calling the ToString method to see if the new start matches with the next Regex.

Is the performance of one or both of the above approaches acceptable, or is there another way which is faster?


  [1]: http://www.dotnetperls.com/stringbuilder-tostring
  [2]: http://blogs.msdn.com/b/miah/archive/2007/10/20/stringbuilder-tostring-vs-reflection.aspx