Below is the fastest code I could create for reversing a String
public static void ReverseFast(string x)
{
string text = x;
StringBuilder reverse = new StringBuilder();
for (int i = text.Length - 1; i >= 0; i--)
{
reverse.Append(text[i]);
}
Console.WriteLine(reverse);
}
I want to address every bottleneck in this equation to make it as fast as possible. The only one I can find so far is the Array Bounds check which I only partially understand. Is there anyway to disable this as I understand it if you use .Length
the compiler decides not to check the bounds but if you are decrementing as I am in the for
loop it still does the boundary check? Can someone convert this to use pointers for me which would avoid the boundary check, I would like to test the speed difference for strings in the range of 100k+ characters.
Based on the comments and posts below this is what I have come up with so far.
public static void ReverseFast(string x)
{
StringBuilder reverse = new StringBuilder(x.Length);
for (int i = x.Length - 1; i >= 0; i--)
{
reverse.Append(x[i]);
}
Console.WriteLine(reverse);
}
This above solution is way faster than the suggested duplicate question answer. This question is really addressing reversal in the range of 5000 * 26 characters +. I would still like to test this out using pointers to really see if there is no bottleneck especially with such large amount of characters.