Quickest Method to Reverse in String in C#.net

前端 未结 11 1903
庸人自扰
庸人自扰 2021-02-02 18:17

I\'m currently writing a quick solution for Euler Problem #4 where one must find the largest palindromic number from the product of two 3-digit numbers.

To identify if a

11条回答
  •  清歌不尽
    2021-02-02 18:46

    The fastest way I have found to reverse a string in C# is with the following code. It's faster reading in 32bits at a time instead of a char's length of 16bits. In debug mode, it is faster until you get to about 93 characters. Anything longer than that Array.Reverse() is faster. Using a release build and running outside of the IDE, this method will blow Array.Reverse() out of the water at any string length.

    char[] MyCharArray = MyString.ToCharArray();
    UIntStringReverse(ref MyCharArray);     //Code to reverse is below.
    string ReversedString = new string(MyCharArray);
    
    
    private static unsafe void UIntStringReverse(ref char[] arr)
    {
        uint Temp;
        uint Temp2;
    
        fixed (char* arrPtr = &arr[0])
        {
            uint* p, q;
            p = (uint*)(arrPtr);
            q = (uint*)(arrPtr + arr.LongLength - 2);
    
            if (arr.LongLength == 2)
            {
                Temp = *p;
                *p = ((Temp & 0xFFFF0000) >> 16) | ((Temp & 0x0000FFFF) << 16); 
                return;
            }
    
            while (p < q)
            {
                Temp = *p;
                Temp2 = *q;
    
                *p = ((Temp2 & 0xFFFF0000) >> 16) | ((Temp2 & 0x0000FFFF) << 16); 
                *q = ((Temp & 0xFFFF0000) >> 16) | ((Temp & 0x0000FFFF) << 16);
    
                p++;
                q--;
            }
        }
    }
    

提交回复
热议问题