The ROT13 algorithm that uses a lookup table performs better but has a much higher initialization cost. It is ideal only for programs that transform huge amounts of text.
using System;
using System.Diagnostics;
static class Rot13
{
static char[] _shift = new char[char.MaxValue];
public static void Init()
{
// Default is not transformed.
for (int i = 0; i < char.MaxValue; i++)
{
_shift[i] = TransformAt((char)i);
}
}
public static string TransformWithTable(string value)
{
// Convert to char array.
char[] array = value.ToCharArray();
// Shift each character.
for (int i = 0; i < array.Length; i++)
{
array[i] = _shift[array[i]];
}
// Return new string.
return new string(array);
}
public static string Transform(string value)
{
char[] array = value.ToCharArray();
for (int i = 0; i < array.Length; i++)
{
array[i] = TransformAt(array[i]);
}
return new string(array);
}
static char TransformAt(char value)
{
int number = (int)value;
if (number >= 'a' && number <= 'z')
{
if (number > 'm')
{
number -= 13;
}
else
{
number += 13;
}
}
else if (number >= 'A' && number <= 'Z')
{
if (number > 'M')
{
number -= 13;
}
else
{
number += 13;
}
}
return (char)number;
}
}
class Program
{
const int _max = 1000000;
static void Main()
{
Rot13.Init();
Console.WriteLine(Rot13.Transform(
"bird is RED"));
Console.WriteLine(Rot13.TransformWithTable(
"bird is RED"));
var s1 = Stopwatch.StartNew();
// Version 1: use if-statements to apply ROT13.
for (int i = 0; i < _max; i++)
{
if (Rot13.Transform(
"bird is RED") ==
"")
{
return;
}
}
s1.Stop();
// Version 2: use lookup table for ROT13.
var s2 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
if (Rot13.TransformWithTable(
"bird is RED") ==
"")
{
return;
}
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString(
"0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString(
"0.00 ns"));
}
}
oveq vf ERQ
oveq vf ERQ
70.60 ns Rot13.Transform
47.35 ns Rot13.TransformWithTable