I have a code that does a lot of comparisons of 64-bit integers, however it should consider the length of the number as if it were formatted as a string. I canβt change the call code, only the function.
The easiest way (besides .ToString (). Length):
(int)Math.Truncate(Math.Log10(x)) + 1;
However, this works rather poorly. Since my application sends only positive values, and the lengths are pretty evenly distributed between 2 and 9 (with some offset to 9), I precomputed the values ββand have if statements:
static int getLen(long x) { if (x < 1000000) { if (x < 100) return 2; if (x < 1000) return 3; if (x < 10000) return 4; if (x < 100000) return 5; return 6; } else { if (x < 10000000) return 7; if (x < 100000000) return 8; if (x < 1000000000) return 9; return (int)Math.Truncate(Math.Log10(x)) + 1;
This allows you to calculate the length on average 4 times.
So, are there any other tricks I can use to speed up this feature?
Edit: this will work as 32-bit code (Silverlight).
Update:
I accepted Normanβs suggestion and changed the ifs a bit, resulting in an average of only 3 comparisons. According to Sean's comment, I deleted Math.Truncate. Together, this increased by about 10%. Thank!
MichaelGG Mar 24 '09 at 23:04 2009-03-24 23:04
source share