public
anonymous / pointless_1321343.cs
Created

Pointless string replace benchmark. Just for fun

  • Download Gist
pointless_1321343.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
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();
}
}
}
results.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
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.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.