Created
January 24, 2017 20:35
-
-
Save bbowyersmyth/c970da26f3ffe560c52f88f11b566761 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 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 int CompareOrdinalIgnoreCaseNew() | |
{ | |
return CompareOrdinalIgnoreCaseNew(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 int CompareOrdinalIgnoreCaseNew(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; | |
int charA; | |
int charB; | |
while (length > 0) | |
{ | |
charA = *a; | |
charB = *b; | |
if (charA == charB || | |
((charA | 0x20) == (charB | 0x20) && | |
(uint)((charA | 0x20) - 97) <= (uint)('z' - 'a'))) | |
{ | |
a++; | |
b++; | |
length--; | |
} | |
else | |
{ | |
goto ReturnDiff; | |
} | |
} | |
return strA.Length - strB.Length; | |
ReturnDiff: | |
return charA - charB; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment