Skip to content

Instantly share code, notes, and snippets.

@TonnyXu
Created February 27, 2010 06:15
Show Gist options
  • Save TonnyXu/316516 to your computer and use it in GitHub Desktop.
Save TonnyXu/316516 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace CSharpBasic
{
class Program
{
public delegate string StringDelegate(string s);
public static void benchmark(string description, StringDelegate d, int times, string s){
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < times; i++ )
{
d(s);
}
sw.Stop();
Console.WriteLine("{0} ticks. {1}(Length:{2}), runs {3} times.", sw.ElapsedTicks, description, s.Length, times);
}
public static string reverseByAPI(string input){
if (string.IsNullOrEmpty(input)) return input;
char[] inputArrary = input.ToCharArray();
Array.Reverse(inputArrary);
return new string(inputArrary);
}
public static string reverseByBitwise(string input){
if (string.IsNullOrEmpty(input)) return input;
int halfLength = input.Length >> 1;
char[] inputArray = input.ToCharArray();
for (int i = 0; i < halfLength; i++ )
{
inputArray[i] ^= inputArray[input.Length - i -1];
inputArray[input.Length - i -1] ^= inputArray[i];
inputArray[i] ^= inputArray[input.Length - i -1];
}
return new string(inputArray);
}
public static string reverseByArray(string input)
{
if (string.IsNullOrEmpty(input)) return input;
int halfLength = input.Length >> 1;
char[] inputArray = input.ToCharArray();
char temp;
for (int i = 0; i < halfLength; i++)
{
temp = inputArray[i];
inputArray[i] = inputArray[input.Length - i - 1];
inputArray[input.Length - i - 1] = temp;
}
return new string(inputArray);
}
public static string StringOfLength(int length)
{
Random random = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++)
{
sb.Append(Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))));
}
return sb.ToString();
}
public static void TestIntegrity(string description, StringDelegate d, string s){
Console.WriteLine("String to be reversed: \"{0}\"",s);
Console.WriteLine("String reversed: \"{0}\", {1}", d(s), description);
Console.WriteLine("-------------");
}
static void Main(string[] args)
{
string[] strs = {"1234567890",
"123",
"日本語"
};
foreach (string s in strs)
{
TestIntegrity("Reversed by API", reverseByAPI, s);
TestIntegrity("Reversed by Array", reverseByArray, s);
}
int[] lengthArray = { 1, 10, 100, 1000, 5000, 10000, 50000};
foreach (int length in lengthArray)
{
string s = StringOfLength(length);
benchmark("ReverseByAPI", reverseByAPI, 10000, s);
benchmark("ReverseByXor", reverseByArray, 10000, s);
Console.WriteLine("===============");
}
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment