-
Notifications
You must be signed in to change notification settings - Fork 7
Description
I'd make a pull request to include some changes, but git is giving me grief.
Was originally looking at http://www.codeproject.com/Tips/447938/High-performance-Csharp-byte-array-to-hex-string-t
Adding it to the tests showed it had better performance than others, but of course has the problem of being 'Unsafe'.
Without changing the basic types in use and method there are some ways to improve ByteArrayToHexViaLookup.
-
Having the table created in the method each time it is called adds an unnecessary overhead.
-
There is a small performance hit to using ForEach when you only use the variable once inside the loop. (http://www.dotnetperls.com/for-foreach)
static readonly string[] HexStringTable = Enumerable.Range(0, 255).Select(i => i.ToString("X2")).ToArray(); static string ByteArrayToHexViaLookup(byte[] bytes) { var result = new StringBuilder(bytes.Length * 2); for (var i = 0; i < bytes.Length; i++) { result.Append(HexStringTable[bytes[i]]); } return result.ToString(); }
The String builder is also slowing this down just a bit - changing how the string is prepared to using an array similar to ByteArrayToHexViaLookupPerByte
static string ByteArrayToHexViaLookupArrayIndex(byte[] bytes)
{
var result = new char[bytes.Length * 2];
for (var i = 0; i < bytes.Length; i++)
{
var val = HexStringTable[bytes[i]];
result[2 * i] = val[0];
result[2 * i + 1] = val[1];
}
return new string(result);
}
Also tried Concat but it does worse than ByteArrayToHexViaLookupAndShift as content size increases
public static string ByteArrayToHexViaLookupConcat(byte[] bytes)
{
var result = new string[bytes.Length];
for (var i = 0; i < bytes.Length; i++)
{
result[i] = HexStringTable[bytes[i]];
}
return string.Concat(result);
}
Trying to see if there was some way to merge the ByteArrayToHexViaLookupPerByte with ideas from the Unsafe method using more direct allocation rather than shifting. The following performs better for larger strings, but takes a hit from double memory alloc on small strings. I have not seen an alternate method for 'casting' an array type.
static string ByteArrayToHexViaLookupPerByteAssignAndBlockCopy(byte[] bytes)
{
var temp = new int[bytes.Length];
for (var i = 0; i < bytes.Length; i++)
{
temp[i] = (int)HexUintTable[bytes[i]];
}
var result = new char[bytes.Length<<1];
Buffer.BlockCopy(temp, 0, result, 0, result.Length<<1);
return new string(result);
}