Skip to content

Instantly share code, notes, and snippets.

@bbowyersmyth
Created January 24, 2017 20:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bbowyersmyth/c970da26f3ffe560c52f88f11b566761 to your computer and use it in GitHub Desktop.
Save bbowyersmyth/c970da26f3ffe560c52f88f11b566761 to your computer and use it in GitHub Desktop.
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