Reverse Strings – Take 2

Well I’ll be damned, I wrote a new version that uses less memory (about half as much!) and it actually is faster – over 10% faster in fact.  Evidently the loop itself is the time consumer:


public unsafe static string StrRevPtr(string s)
{
  int len = s.Length;


  char[] srcchars = s.ToCharArray();
  char b;


  fixed(char *src = srcchars)
  {
    for(int i = 0 ; i < len / 2 ; i++)
    {
      b = src[i];
      src[i] = src[len-i-1];
      src[len-i-1] = b;
    }
  }


  return new string(srcchars);
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s