Created
July 5, 2013 22:19
-
-
Save anonymous/5937596 to your computer and use it in GitHub Desktop.
Pointless string replace benchmark. Just for fun
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace ConsoleApplication1 | |
{ | |
using System; | |
using System.Diagnostics; | |
using System.Text; | |
internal class Program | |
{ | |
const string TestData = "Some Random Place & Some' Chars. "; | |
const int Iterations = 1000000; | |
private static void Main(string[] args) | |
{ | |
Test(BenchmarkOverhead); | |
Test(StringCleanA); | |
Test(StringCleanB); | |
Console.ReadLine(); | |
} | |
static void Test(Func<string, bool> function) | |
{ | |
Console.Write("{0}... ", function.Method.Name); | |
Stopwatch sw = Stopwatch.StartNew(); | |
for (int i = 0; i < Iterations; i++) | |
{ | |
function(TestData); | |
} | |
sw.Stop(); | |
Console.WriteLine(" {0}ms", sw.ElapsedMilliseconds); | |
GC.Collect(); | |
} | |
private static bool BenchmarkOverhead(string str) | |
{ | |
return true; | |
} | |
private static bool StringCleanA(string str) | |
{ | |
StringExtensionA.Clean(str); | |
return true; | |
} | |
private static bool StringCleanB(string str) | |
{ | |
StringExtensionB.Clean(str); | |
return true; | |
} | |
} | |
public static class StringExtensionA | |
{ | |
public static string Clean(string s) | |
{ | |
return (new StringBuilder(s)).Replace("&", "and").Replace(",", "") | |
.Replace(" ", " ").Replace(" ", "-").Replace("'", "") | |
.Replace(".", "").Replace("eacute;", "é").ToString().ToLower(); | |
} | |
} | |
public static class StringExtensionB | |
{ | |
public static string Clean(string s) | |
{ | |
StringBuilder sb = new StringBuilder(s); | |
sb.Replace("&", "and"); | |
sb.Replace(",", ""); | |
sb.Replace(" ", " "); | |
sb.Replace(" ", "-"); | |
sb.Replace("'", ""); | |
sb.Replace(".", ""); | |
sb.Replace("eacute;", "é"); | |
return sb.ToString().ToLower(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
BenchmarkOverhead... 14ms | |
StringCleanA... 2943ms | |
StringCleanB... 2901ms | |
BenchmarkOverhead... 13ms | |
StringCleanA... 2937ms | |
StringCleanB... 2924ms | |
BenchmarkOverhead... 13ms | |
StringCleanA... 2919ms | |
StringCleanB... 2892ms | |
BenchmarkOverhead... 13ms | |
StringCleanA... 2907ms | |
StringCleanB... 2876ms | |
Tests repeated 4 times to give a mean. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment