Today's post will be about performance. More specifically about converting hex string into decimal number faster than using built-in .NET Framework methods.
I will compare performance of three methods used to convert hex into decimal number. Two of those methods are built into .NET Framework.
1) Convert.ToInt32(hexNumberString, 16)
2) int.Parse(hexNumber, NumberStyles.HexNumber);
3) Custom method using pre-populated table. Let us call it TableConvert.
Here's the code for the TableConvert class. This class just illustrates the idea behind pre-populated table - it is not production code.
class TableConvert
{
static sbyte[] unhex_table =
{ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1
,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1
,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1
,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
};
public static int Convert(string hexNumber)
{
int decValue = unhex_table[(byte)hexNumber[0]];
for (int i = 1; i < hexNumber.Length; i++)
{
decValue *= 16;
decValue += unhex_table[(byte)hexNumber[i]];
}
return decValue;
}
}
The approach uses simple technique of pre-populated table of hex-to-decimal values and some simple math. To measure performance of these three methods I've wrote small test application that performed conversion in the loop and measured time.
Tests were made using Intel Core i7 2.80 GHz, .NET Framework 4.0. Time measurements were made in ticks using Stopwatch class.
Results:
Hex string: FF01
Iterations | TableConvert | Convert Method | Parse Method |
100 | 28 | 35 | 63 |
10000 | 2134 | 2593 | 5915 |
1000000 | 191935 | 252252 | 433490 |
Hex string: 4AB201
Iterations | TableConvert | Convert Method | Parse Method |
100 | 26 | 27 | 47 |
10000 | 1930 | 2775 | 4284 |
1000000 | 192801 | 269016 | 481308 |
No comments:
Post a Comment