Jam*_*ing 19 .net string math performance
在.NET中,如果将字符表示为字符串,那么查找字符整数长度的最佳方法是什么?
例如
1 = 1个字符
10 = 2个字符
99 = 2个字符
100 = 3个字符
1000 = 4个字符
显而易见的答案是将int转换为字符串并获取其长度,但我希望尽可能获得最佳性能,而无需创建新字符串的开销.
stm*_*max 37
你可以使用logartihms来计算int的长度:
public static int IntLength(int i) {
if (i <= 0) throw new ArgumentOutOfRangeException();
return (int)Math.Floor(Math.Log10(i)) + 1;
}
Run Code Online (Sandbox Code Playgroud)
测试通过:
[Test]
public void TestIntLength() {
Assert.AreEqual(1, IntLength(1));
Assert.AreEqual(1, IntLength(9));
Assert.AreEqual(2, IntLength(10));
Assert.AreEqual(2, IntLength(99));
Assert.AreEqual(3, IntLength(100));
Assert.AreEqual(3, IntLength(999));
Assert.AreEqual(4, IntLength(1000));
Assert.AreEqual(10, IntLength(int.MaxValue));
}
Run Code Online (Sandbox Code Playgroud)
快速测试表明,log-method的速度比int.ToString()快4倍.
下面的GvS所示的方法(使用if语句)比log方法快6倍(!):
public static int IntLengthIf(int i) {
if (i < 10) return 1;
if (i < 100) return 2;
if (i < 1000) return 3;
if (i < 10000) return 4;
if (i < 100000) return 5;
if (i < 1000000) return 6;
if (i < 10000000) return 7;
if (i < 100000000) return 8;
if (i < 1000000000) return 9;
throw new ArgumentOutOfRangeException();
}
Run Code Online (Sandbox Code Playgroud)
以下是数字1到10000000的确切时间:
IntLengthToString: 4205ms
IntLengthLog10: 1122ms
IntLengthIf: 201ms
Run Code Online (Sandbox Code Playgroud)
GvS*_*GvS 12
如果输入范围为0-10000
if (i < 10) return 1;
if (i < 100) return 2;
if (i < 1000) return 3;
if (i < 10000) return 4;
// etc
Run Code Online (Sandbox Code Playgroud)