Skip to content
This repository was archived by the owner on Dec 18, 2023. It is now read-only.

Commit da6c3d5

Browse files
miknojSergeyKanzhelev
authored andcommitted
Improve performance of ByteToHexCharArray (#56)
- Current implementation performanced many allocations. - Changed to a method that utilizes a byte to hex lookup table.
1 parent 44a038c commit da6c3d5

File tree

1 file changed

+19
-18
lines changed

1 file changed

+19
-18
lines changed

src/OpenCensus/Utils/Arrays.cs

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ namespace OpenCensus.Utils
2121

2222
internal static class Arrays
2323
{
24+
private static readonly uint[] ByteToHexLookupTable = CreateLookupTable();
25+
2426
public static bool Equals(byte[] array1, byte[] array2)
2527
{
2628
if (array1 == array2)
@@ -85,28 +87,27 @@ internal static int HexCharToInt(char c)
8587
throw new ArgumentOutOfRangeException("Invalid character: " + c);
8688
}
8789

88-
internal static char[] ByteToHexCharArray(byte b)
90+
// https://stackoverflow.com/a/24343727
91+
internal static uint[] CreateLookupTable()
8992
{
90-
int low = b & 0x0f;
91-
int high = (b & 0xf0) >> 4;
92-
char[] result = new char[2];
93-
if (high > 9)
94-
{
95-
result[0] = (char)(high - 10 + 'a');
96-
}
97-
else
93+
uint[] table = new uint[256];
94+
for (int i = 0; i < 256; i++)
9895
{
99-
result[0] = (char)(high + '0');
96+
string s = i.ToString("x2");
97+
table[i] = (uint)s[0];
98+
table[i] += (uint)s[1] << 16;
10099
}
101100

102-
if (low > 9)
103-
{
104-
result[1] = (char)(low - 10 + 'a');
105-
}
106-
else
107-
{
108-
result[1] = (char)(low + '0');
109-
}
101+
return table;
102+
}
103+
104+
// https://stackoverflow.com/a/24343727
105+
internal static char[] ByteToHexCharArray(byte b)
106+
{
107+
char[] result = new char[2];
108+
109+
result[0] = (char)ByteToHexLookupTable[b];
110+
result[1] = (char)(ByteToHexLookupTable[b] >> 16);
110111

111112
return result;
112113
}

0 commit comments

Comments
 (0)