Skip to content

Instantly share code, notes, and snippets.

@benaadams
Last active August 7, 2018 12:36
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 benaadams/96817fc81aee26053416eb1f3cdf54c9 to your computer and use it in GitHub Desktop.
Save benaadams/96817fc81aee26053416eb1f3cdf54c9 to your computer and use it in GitHub Desktop.
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System;
namespace hash
{
public class Program
{
const int Iterations = 10;
static void Main(string[] args)
{
BenchmarkRunner.Run<Program>();
}
[Params(
"",
"1",
"12",
"123",
"1234",
"12345",
"123456",
"1234567",
"12345678",
"123456789",
"1234567890",
"12345678901234567890",
"1234567890123456789012345678901234567890",
"12345678901234567890123456789012345678901234567890123456789012345678901234567890",
"1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"
)]
public string Input { get; set; }
[Benchmark(OperationsPerInvoke = Iterations, Baseline = true)]
public int CurrentHashCode()
{
var input = Input;
var hashCode = 0;
for (var i = 0; i < Iterations; i++)
{
hashCode += CurrentHashCode(input);
}
return hashCode;
}
[Benchmark(OperationsPerInvoke = Iterations)]
public int NewHashCode()
{
var input = Input;
var hashCode = 0;
for (var i = 0; i < Iterations; i++)
{
hashCode += HashCode(input);
}
return hashCode;
}
public int CurrentHashCode(string str)
{
unsafe
{
fixed (char* src = str)
{
int hash1 = 5381;
int hash2 = hash1;
int c;
char* s = src;
while ((c = s[0]) != 0)
{
hash1 = ((hash1 << 5) + hash1) ^ c;
c = s[1];
if (c == 0)
break;
hash2 = ((hash2 << 5) + hash2) ^ c;
s += 2;
}
return hash1 + (hash2 * 1566083941);
}
}
}
public int HashCode(string str)
{
unsafe
{
fixed (char* src = str)
{
int hash1 = 5381;
int hash2 = hash1;
char* current = src;
char* end = current + str.Length;
while (current < end - 1)
{
hash1 = ((hash1 << 5) + hash1) ^ current[0];
hash2 = ((hash2 << 5) + hash2) ^ current[1];
current += 2;
}
if (current < end)
{
hash1 = ((hash1 << 5) + hash1) ^ current[0];
}
return hash1 + (hash2 * 1566083941);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment