.NET Core 5 + Benchmark 테스트 결과입니다.
Score: 1690.9 / 186.5 = 9.066487935656836
변환 코드
const string table = "0123456789ABCDEF";
return string.Create(Size * 2, _buffer, static(span, buffer) =>
{
for (int i = 0; i < Size; i++)
{
span[0] = table[(buffer[i] & 0xF0) >> 4];
span[1] = table[buffer[i] & 0x0F];
span = span.Slice(2);
}
});
전체 테스트 코드
using System;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Jobs;
[SimpleJob(RuntimeMoniker.NetCoreApp50)]
public class ByteHex16
{
private const int Size = 8192 * 10000;
private byte[] _buffer;
[GlobalSetup]
public void Setup()
{
_buffer = new byte[Size];
new Random().NextBytes(_buffer);
}
[Benchmark]
public string BitConverter()
{
return System.BitConverter.ToString(_buffer).Replace("-", "");
}
[Benchmark]
public string Dimohy()
{
var bc = new char[Size * 2];
for (var i = 0; i < _buffer.Length; i++)
{
var index = i << 1;
(bc[index], bc[index + 1]) = ToHexa(_buffer[i]);
}
return new string(bc);
static (char, char) ToHexa(byte d)
{
var a = (d & 0xF0) >> 4;
var b = d & 0x0F;
if (a < 10)
a += '0';
else
a += 'A' - 10;
if (b < 10)
b += '0';
else
b += 'A' - 10;
return ((char)a, (char)b);
}
}
[Benchmark]
public string EvanChoi()
{
const string table = "0123456789ABCDEF";
return string.Create(Size * 2, _buffer, static(span, buffer) =>
{
for (int i = 0; i < Size; i++)
{
span[0] = table[(buffer[i] & 0xF0) >> 4];
span[1] = table[buffer[i] & 0x0F];
span = span.Slice(2);
}
});
}
}