gpt4 book ai didi

.net - 我应该推出我自己的 ParseInt32 版本吗?

转载 作者:行者123 更新时间:2023-12-02 05:21:49 26 4
gpt4 key购买 nike

我正在编写一个高性能解析器,在我看来 Int32.Parse 可能太慢了。我编写了一个假设输入正确的简单版本,并且它的性能要好得多。那么我应该创建自己的版本吗?或者是否有另一种更快的方法可用?

我的方法是这样的:

// parse simple int, assuming relatively correct input (i.e. all digits)
public static int ParseInt32Simply(string str) {
if (str == null) throw new ArgumentNullException("str");
if (str.Length == 0) throw new ArgumentException("str is empty");

int sign = 1, index = 0;
if (str[0] == '-') { sign = -1; index = 1; }
else if (str[0] == '+') { index = 1; }

int result = 0;
for (; index < str.Length; ++index) {
result = 10 * result + (str[index] - '0');
}

if (result < 0) throw new OverflowException(str + " is too large for Int32");

return result * sign;
}

我的结果与内置的等效结果非常不同:

Int32.Parse      took 8.2775453 seconds
ParseInt32Simply took 0.6511523 seconds
Int32.Parse took 6.7625807 seconds
ParseInt32Simply took 0.4677390 seconds

(在我的机器上运行 2500 万次迭代;P4 3 GHz,运行 VS 2008 SP1)

那么,我应该使用我的版本吗?或者我可以使用其他方法吗?

最佳答案

您是否分析过您的代码以确定 ParseInt32 实际上是瓶颈?我不会替换您正在编写代码的环境的“标准库”的一部分,除非您确定您会看到好处。

关于.net - 我应该推出我自己的 ParseInt32 版本吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/416182/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com