Last active
April 29, 2017 12:46
-
-
Save ahydrax/477fedfe5a44bb49ff862b554694a4f1 to your computer and use it in GitHub Desktop.
Performance comparison between existing and proposed implementation of method ToHexString
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 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>(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Local run