顶在我的机器,AV你的代码是最快的(你的代码在第二位)。
注意单位!蜱是100纳秒增量。
SplitReplace takes 0.961795 ticks per call
Split takes 0.747009 ticks per call
Regex takes 2.512739 ticks per call
WithLinq takes 2.59299 ticks per call
我的变化仅仅是只分(不更换):
string[] parts = val.Split('(', ')');
return parts[1];
测试代码...
[Test]
public void SO()
{
const string input = "name +value (email)";
TestGivenMethod(input, SplitReplace, "SplitReplace");
TestGivenMethod(input, JustSplit, "Split");
TestGivenMethod(input, WithRegex, "Regex");
TestGivenMethod(input, WithLinq, "WithLinq");
}
private void TestGivenMethod(string input, Func<string, string> method, string name)
{
Assert.AreEqual("email", method(input));
var sw = Stopwatch.StartNew();
string res = "";
for (int i = 0; i < 1000000; i++)
{
var email = method(input);
res = email;
}
sw.Stop();
Assert.AreEqual("email", res);
Console.WriteLine("{1} takes {0} ticks per call", sw.ElapsedTicks/1000000.0, name);
}
string SplitReplace(string val)
{
string[] parts = val.Split('(');
return parts[1].Replace(")", String.Empty);
}
string JustSplit(string val)
{
string[] parts = val.Split('(', ')');
return parts[1];
}
private static Regex method3Regex = new Regex(@"\(([\[email protected]]+)\)");
string WithRegex(string val)
{
return method3Regex.Match(val).Groups[1].Value;
}
string WithLinq(string val)
{
return new string(val.SkipWhile(c => c != '(').Skip(1).TakeWhile(c => c != ')').ToArray());
}
是多么糟糕的表现呢?我问,因为你想要最好的表现,但没有提供任何指标来解决问题。 – 2011-12-30 16:17:26
性能之间的差异通常是微不足道的,以至于只有在以下情况下才会注意到它们:运行大型处理循环 - 或 - 运行视频游戏。如果没有这些,你不应该解决“哪种性能更好”,除非你真的通过使用产品来确定性能是一个问题。 – Dracorat 2011-12-30 16:26:44