Tuesday, May 17, 2005

Performance: Fastest string reversing algorithms... (final results)

Performance: Fastest string reversing algorithms... (final results)


private static string ReverseUsingCharArrayCopy(string input) {
char[] reversed = input.ToCharArray();

for(int i = 0, j = reversed.Length - 1; i < j; i++, j--) {
reversed[j] = input[i];
reversed[i] = input[j];
// char temp = reversed[i];
// reversed[i] = reversed[j];
// reversed[j] = temp;
}
return new String(reversed);
}


private static string ReverseUsingCharArrayInline(string input) {
char[] reversed = new char[input.Length];
for(int i = 0, j = reversed.Length - 1; i <= j; i++, j--) {
reversed[i] = input[j];
reversed[j] = input[i];
}
return new String(reversed);

}


private static string ReverseUsingStringBuilderInline(string input) {
StringBuilder sb = new StringBuilder(input);
for(int i = 0, j = input.Length - 1; i <= j; i++, j--) {
sb[i] = input[j];
sb[j] = input[i];
}
return sb.ToString();
}


unsafe static void ReverseString(string source)
{
int y=source.Length-1;
int mid=source.Length/2;
fixed(char* sfixed=source)
{
char* s=sfixed;
char t;
for(int x=0; x{
t=s[x];
s[x]=s[y];
s[y]=t;
} }
}


# re: Performance: Fastest string reversing algorithms... (final results) 6/12/2004 3:54 PM Justin Rogers

for unsafe code:

One of the tenets of the first competition was that thread safety was a must. Your method, for obvious reasons is not thread safe because you overwrite the string in place. If, however, you copied your string, then everything would be fine, so I'll take your algorithm and append a string output = string.Copy(input);, and then work over the copied string. That'll prove it to be thread safe.

Another thing to note is that since we are making a proper copy of the string first, and we are not changing the contents of the string, only the ordering, we can hopefully disregard negative side effects of using the NLS bits...

I'll make a posting later with the methods devised, there are faster versions of the algorithm than what you posted when using unsafe code.

0 Comments:

Post a Comment

<< Home