Skip to content

Instantly share code, notes, and snippets.

@akatakritos
Created June 1, 2018 18:44
Show Gist options
  • Save akatakritos/a0c9be46d222ce483eb0f0fcbb1d7af8 to your computer and use it in GitHub Desktop.
Save akatakritos/a0c9be46d222ce483eb0f0fcbb1d7af8 to your computer and use it in GitHub Desktop.
Stripping Non-AlphaNumerics in C# Benchmark
[MemoryDiagnoser]
public class Benchmark1
{
[Params("555-55-5555", "555-123-fsdfjksdf-xxx_fdslfs fkslfd_fkdlsf")]
public string Input { get; set; }
[Benchmark]
public string StringBuilderForeach()
{
var sb = new StringBuilder();
foreach (var c in Input)
{
if (char.IsLetterOrDigit(c))
sb.Append(c);
}
return sb.ToString();
}
[Benchmark]
public string StringBuilderFor()
{
var sb = new StringBuilder();
for(int i = 0; i < Input.Length; i++)
{
var c = Input[i];
if (char.IsLetterOrDigit(c))
sb.Append(c);
}
return sb.ToString();
}
static readonly Regex _r = new Regex(@"[^a-zA-Z0-9]");
static readonly Regex _rCompiled = new Regex(@"[^a-zA-Z0-9]", RegexOptions.Compiled);
[Benchmark]
public string RegularExpression()
{
return _r.Replace(Input, "");
}
[Benchmark]
public string RegularExpressionCompiled()
{
return _rCompiled.Replace(Input, "");
}
}
BenchmarkDotNet=v0.10.14, OS=Windows 10.0.17134
Intel Core i7-6650U CPU 2.20GHz (Skylake), 1 CPU, 4 logical and 2 physical cores
Frequency=2156250 Hz, Resolution=463.7681 ns, Timer=TSC
  [Host]     : .NET Framework 4.7.1 (CLR 4.0.30319.42000), 32bit LegacyJIT-v4.7.3101.0
  DefaultJob : .NET Framework 4.7.1 (CLR 4.0.30319.42000), 32bit LegacyJIT-v4.7.3101.0

Method Input Mean Error StdDev Median Gen 0 Allocated
StringBuilderForeach 555-123-fsdfjksdf-xxx_fdslfs fkslfd_fkdlsf 590.4 ns 11.853 ns 34.008 ns 579.6 ns 0.1593 336 B
StringBuilderFor 555-123-fsdfjksdf-xxx_fdslfs fkslfd_fkdlsf 557.2 ns 7.810 ns 6.924 ns 557.4 ns 0.1593 336 B
RegularExpression 555-123-fsdfjksdf-xxx_fdslfs fkslfd_fkdlsf 2,937.3 ns 54.250 ns 50.745 ns 2,926.6 ns 0.5112 1080 B
RegularExpressionCompiled 555-123-fsdfjksdf-xxx_fdslfs fkslfd_fkdlsf 2,556.4 ns 49.963 ns 61.359 ns 2,556.6 ns 0.5112 1080 B
StringBuilderForeach 555-55-5555 138.1 ns 2.780 ns 3.415 ns 137.6 ns 0.0494 104 B
StringBuilderFor 555-55-5555 147.9 ns 3.997 ns 11.468 ns 144.4 ns 0.0494 104 B
RegularExpression 555-55-5555 1,123.5 ns 53.205 ns 154.356 ns 1,061.6 ns 0.1659 352 B
RegularExpressionCompiled 555-55-5555 955.9 ns 49.846 ns 146.190 ns 880.4 ns 0.1659 352 B
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment