Extension Methods to Reverse a String and StringBuilder Object






4.83/5 (5 votes)
This is an alternative to "Extension Methods to Reverse a String and StringBuilder Object".
Less code, and much faster, would be:
public static string ReverseSB(string text) {
int len = text.Length;
if (len>1) {
StringBuilder sb=new StringBuilder(text);
int pivotPos=len/2;
len--;
for (int i = 0; i < pivotPos; i++) {
int j=len-i;
char temp=sb[i];
sb[i]=sb[j];
sb[j]=temp;
}
text=sb.ToString();
}
return text;
}
or its extension-method variant. Tested on a 80-char string
, it is 8 times faster. The reason should be clear: John's code creates 6 string
s for each character pair, as each SubString
, Remove
, Insert
method generates a new string
object, copying the relevant characters.
:)