Created
September 14, 2018 13:58
-
-
Save szehetner/c2044f703783bc7a19706cf7ead5805d to your computer and use it in GitHub Desktop.
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
using System; | |
using System.Text.RegularExpressions; | |
using BenchmarkDotNet.Attributes; | |
namespace TestApp | |
{ | |
[MemoryDiagnoser] | |
public class TextNormalizerBenchmark | |
{ | |
private string _valueLowerCase = "headername"; | |
private string _valueUpperCase = "HeaderName"; | |
[Params("headername", "HeaderName")] | |
public string InputValue; | |
private static readonly Regex ValidKeyRegex = new Regex("^[.a-z0-9_-]+$"); | |
[Benchmark(Baseline = true)] | |
public void ToLower() | |
{ | |
var normalized = InputValue.ToLowerInvariant(); | |
if (!ValidKeyRegex.IsMatch(normalized)) | |
throw new Exception(); | |
} | |
[Benchmark] | |
public void ToLowerNoRegex() | |
{ | |
if (!IsValid(InputValue, out bool isLowercase)) | |
throw new Exception(); | |
string normalized; | |
if (!isLowercase) | |
normalized = InputValue.ToLowerInvariant(); | |
else | |
normalized = InputValue; | |
} | |
private bool IsValid(string input, out bool isLowercase) | |
{ | |
isLowercase = true; | |
for (int i = 0; i < input.Length; i++) | |
{ | |
char c = input[i]; | |
if ('a' <= c && c <= 'z' | |
|| '0' <= c && c <= '9' | |
|| c == '.' | |
|| c == '_' | |
|| c == '-') | |
continue; | |
if ('A' <= c && c <= 'Z') | |
{ | |
isLowercase = false; | |
continue; | |
} | |
return false; | |
} | |
return true; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment