问题描述
我有一些code,做了很多的64位整数比较,但它必须考虑到数字的长度,因为如果它被格式化为一个字符串。我不能改变调用code,只有功能。
I have some code that does a lot of comparisons of 64-bit integers, however it must take into account the length of the number, as if it was formatted as a string. I can't change the calling code, only the function.
最简单的方法(除了的ToString()的长度。)是:
The easiest way (besides .ToString().Length) is:
(int)Math.Truncate(Math.Log10(x)) + 1;
不过,执行相当差。由于我的应用程序只发送正值,且长度相当均匀2和9之间的分布(与朝9一些偏见),我precomputed的值,并有if语句:
However that performs rather poorly. Since my application only sends positive values, and the lengths are rather evenly distributed between 2 and 9 (with some bias towards 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; // Very uncommon
}
}
此允许长度平均为4比较来计算。
This lets the length be computed with an average of 4 compares.
那么,还有没有其他的技巧,我可以使用,使这个功能更快?
So, are there any other tricks I can use to make this function faster?
编辑:这将运行32位code(Silverlight的)
This will be running as 32-bit code (Silverlight).
更新:
我把诺曼的建议,改变了IFS张望了一下导致平均只有3比较。按照肖恩的评论,我删除了Math.Truncate。一起,这促进了约10%的事情。谢谢!
I took Norman's suggestion and changed the ifs around a bit to result in an average of only 3 compares. As per Sean's comment, I removed the Math.Truncate. Together, this boosted things about 10%. Thanks!
推荐答案
两点建议:
- 个人资料,并把常见的情况第一。
- 执行二进制搜索,以尽量减少comparions在最坏的情况下的数量。您可以使用当中正好三个比较8备选方案决定。
该组合可能不会买你多少,除非分布是非常偏斜。
This combination probably doesn't buy you much unless the distribution is very skew.
这篇关于最快的计算一个整数的十进制长度的方法吗? (。净)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!