【发布时间】:2011-12-27 20:13:24
【问题描述】:
为什么string不能使用流利的语言?
例如:
var x = "asdf1234";
var y = new string(x.TakeWhile(char.IsLetter).ToArray());
难道没有更好的方法将IEnumerable<char> 转换为string?
这是我做的一个测试:
class Program
{
static string input = "asdf1234";
static void Main()
{
Console.WriteLine("1000 times:");
RunTest(1000, input);
Console.WriteLine("10000 times:");
RunTest(10000,input);
Console.WriteLine("100000 times:");
RunTest(100000, input);
Console.WriteLine("100000 times:");
RunTest(100000, "ffff57467");
Console.ReadKey();
}
static void RunTest( int times, string input)
{
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < times; i++)
{
string output = new string(input.TakeWhile(char.IsLetter).ToArray());
}
sw.Stop();
var first = sw.ElapsedTicks;
sw.Restart();
for (int i = 0; i < times; i++)
{
string output = Regex.Match(input, @"^[A-Z]+",
RegexOptions.IgnoreCase).Value;
}
sw.Stop();
var second = sw.ElapsedTicks;
var regex = new Regex(@"^[A-Z]+",
RegexOptions.IgnoreCase);
sw.Restart();
for (int i = 0; i < times; i++)
{
var output = regex.Match(input).Value;
}
sw.Stop();
var third = sw.ElapsedTicks;
double percent = (first + second + third) / 100;
double p1 = ( first / percent)/ 100;
double p2 = (second / percent )/100;
double p3 = (third / percent )/100;
Console.WriteLine("TakeWhile took {0} ({1:P2}).,", first, p1);
Console.WriteLine("Regex took {0}, ({1:P2})." , second,p2);
Console.WriteLine("Preinstantiated Regex took {0}, ({1:P2}).", third,p3);
Console.WriteLine();
}
}
结果:
1000 times:
TakeWhile took 11217 (62.32%).,
Regex took 5044, (28.02%).
Preinstantiated Regex took 1741, (9.67%).
10000 times:
TakeWhile took 9210 (14.78%).,
Regex took 32461, (52.10%).
Preinstantiated Regex took 20669, (33.18%).
100000 times:
TakeWhile took 74945 (13.10%).,
Regex took 324520, (56.70%).
Preinstantiated Regex took 172913, (30.21%).
100000 times:
TakeWhile took 74511 (13.77%).,
Regex took 297760, (55.03%).
Preinstantiated Regex took 168911, (31.22%).
结论:我怀疑什么是更好的选择,我想我会继续TakeWhile,这只是第一次运行时最慢的。
无论如何,我的问题是是否有任何方法可以通过重新设置TakeWhile 函数的结果来优化性能。
【问题讨论】:
-
请解释一下“最好”是什么意思:最快?最不占内存?最容易理解?
-
@LukeH 我已经决定选择什么:最快的。我的问题是是否有比
new string(x.TakeWhile(p).ToArray)更好的方法 -
@LukeH:可能想取消删除您的解决方案:它比我的要快很多
-
所有这些答案都引出了一个问题——为什么 IEnumerable
.ToString() 没有在 System.Linq.Enumerable 中被覆盖 -
@Dave,您不能使用扩展方法覆盖基本函数。但是,I would want to see 是
string构造函数中的重载,它采用IEnumerable<char>。
标签: .net regex performance performance-testing