Created
January 30, 2017 21:26
-
-
Save bbowyersmyth/eb7ebcf7829f0275575541f2334d2826 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 BenchmarkDotNet.Attributes; | |
using System; | |
namespace ConsoleApplication2 | |
{ | |
[Config("jobs=RyuJitX64")] | |
public unsafe class CompareOrdinalIgnoreCase | |
{ | |
[Params(1, 5, 12, 50, 100)] | |
public int length = 0; | |
string test1; | |
string test2; | |
[Setup] | |
public void Setup() | |
{ | |
test1 = new string('A', length); | |
test2 = new string('A', length); | |
} | |
[Benchmark] | |
public int CompareOrdinalIgnoreCaseOld() | |
{ | |
return CompareOrdinalIgnoreCaseOld(test1, test2); | |
} | |
[Benchmark] | |
public bool EqualsIgnoreCaseAsciiHelper() | |
{ | |
return EqualsIgnoreCaseAsciiHelper(test1, test2); | |
} | |
public int CompareOrdinalIgnoreCaseOld(String strA, String strB) | |
{ | |
int length = Math.Min(strA.Length, strB.Length); | |
fixed (char* ap = strA) fixed (char* bp = strB) | |
{ | |
char* a = ap; | |
char* b = bp; | |
while (length != 0) | |
{ | |
int charA = *a; | |
int charB = *b; | |
// uppercase both chars - notice that we need just one compare per char | |
if ((uint)(charA - 'a') <= (uint)('z' - 'a')) charA -= 0x20; | |
if ((uint)(charB - 'a') <= (uint)('z' - 'a')) charB -= 0x20; | |
//Return the (case-insensitive) difference between them. | |
if (charA != charB) | |
return charA - charB; | |
// Next char | |
a++; b++; | |
length--; | |
} | |
return strA.Length - strB.Length; | |
} | |
} | |
public static bool EqualsIgnoreCaseAsciiHelper(String strA, String strB) | |
{ | |
int length = strA.Length; | |
fixed (char* ap = strA) fixed (char* bp = strB) | |
{ | |
char* a = ap; | |
char* b = bp; | |
while (length != 0) | |
{ | |
int charA = *a; | |
int charB = *b; | |
if (charA == charB || | |
((charA | 0x20) == (charB | 0x20) && | |
(uint)((charA | 0x20) - 'a') <= (uint)('z' - 'a'))) | |
{ | |
a++; | |
b++; | |
length--; | |
} | |
else | |
{ | |
goto ReturnFalse; | |
} | |
} | |
return true; | |
ReturnFalse: | |
return false; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment