【发布时间】:2010-01-15 13:58:56
【问题描述】:
我编写了以下方法从字符串中删除括号中的命名空间。
我想让它尽可能快。
有没有办法加快下面的代码?
using System;
namespace TestRemoveFast
{
class Program
{
static void Main(string[] args)
{
string[] tests = {
"{http://company.com/Services/Types}ModifiedAt",
"{http://company.com/Services/Types}CreatedAt"
};
foreach (var test in tests)
{
Console.WriteLine(Clean(test));
}
Console.ReadLine();
}
static string Clean(string line)
{
int pos = line.IndexOf('}');
if (pos > 0)
return line.Substring(pos + 1, line.Length - pos - 1);
else
return line;
}
}
}
【问题讨论】:
-
以下哪一项更快? line.Substring(pos + 1) 与 line.Substring(pos + 1, line.Length - pos - 1)。我想你之前测试过,然后选择了后者?!
-
这并不慢。在我看来,添加 RegEx 将是不必要的开销。
-
您可以将 pos+1 移动到一个变量中,并将其用于开始和减法。但是我们说的是纳秒;)但是它可以节省+1和-1。也是纳秒。将 line.IndexOf('}') 更改为 line.IndexOf('}', 8, line.Length)。保存一个方法调用并扫描起始字节。
标签: c# text performance