Skip to content

Instantly share code, notes, and snippets.

@ahydrax
Last active April 29, 2017 12:46
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 ahydrax/477fedfe5a44bb49ff862b554694a4f1 to your computer and use it in GitHub Desktop.
Save ahydrax/477fedfe5a44bb49ff862b554694a4f1 to your computer and use it in GitHub Desktop.
Performance comparison between existing and proposed implementation of method ToHexString
using System;
using System.Linq;
using System.Text;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
namespace ToHexStringPerf
{
public class Tests
{
public static readonly byte[] testBytes = Enumerable.Repeat(Enumerable.Range(-127, 127), 4).SelectMany(x => x).Select(x => (byte)x).ToArray();
[Benchmark]
public void MongoDbImplementation()
{
ToHexStringMongoDB(testBytes);
}
public static string ToHexStringMongoDB(byte[] bytes)
{
if (bytes == null)
{
throw new ArgumentNullException("bytes");
}
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.AppendFormat("{0:x2}", b);
}
return sb.ToString();
}
[Benchmark]
public void HandCoded()
{
ToHexStringHandCoded(testBytes);
}
public static string ToHexStringHandCoded(byte[] bytes)
{
if (bytes == null)
{
throw new ArgumentNullException(nameof(bytes));
}
var c = new char[bytes.Length * 2];
byte b;
for (int bx = 0, cx = 0; bx < bytes.Length; ++bx, ++cx)
{
b = ((byte)(bytes[bx] >> 4));
c[cx] = (char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30);
b = ((byte)(bytes[bx] & 0x0F));
c[++cx] = (char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30);
}
return new string(c);
}
}
class Program
{
static void Main(string[] args)
{
var summary = BenchmarkRunner.Run<Tests>();
}
}
}
@ahydrax
Copy link
Author

ahydrax commented Apr 29, 2017

Local run

BenchmarkDotNet=v0.10.5, OS=Windows 10.0.15063
Processor=Intel Core i5-2400 CPU 3.10GHz (Sandy Bridge), ProcessorCount=4
Frequency=3037251 Hz, Resolution=329.2451 ns, Timer=TSC
  [Host]     : Clr 4.0.30319.42000, 32bit LegacyJIT-v4.7.2046.0
  DefaultJob : Clr 4.0.30319.42000, 32bit LegacyJIT-v4.7.2046.0

Method Mean Error StdDev
MongoDbImplementation 97.146 us 1.1451 us 1.0711 us
HandCoded 1.932 us 0.0216 us 0.0202 us

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment