【发布时间】:2010-10-14 12:12:23
【问题描述】:
鉴于以下针对60% toleration 的输入
"STACKOVERflow is a quesTions and ANSwers weBSITE"
我希望得到以下输出
// Extra spaces just to show %s
// 69% 50% 100% 22%! 33% 42% 14%
"Stackoverflow Is A QuesTions And ANSwers Website"
Questions 和 Answers 具有大写字符,但它们代表的字符串少于 60%,因此应保留。然后我想将每个字符串的第一个字符转换为大写。
我目前正在使用这种方法
public static class StringExtender
{
public static string ToTitleCase(this string str, double preserve)
{
return String.Join(" ",
str.Split(' ')
.Select(x => (x.Count(y => y.ToString() == y.ToString().ToUpper()) / (double)x.Length * 100) > preserve ? x.ToLower() : x)
.Select(x =>
String.Join(String.Empty,
x.Select((y, z) => z == 0 ? y.ToString().ToUpper() : y.ToString()).ToArray()
)
).ToArray()
);
}
}
第一次运行时,我得到15000 滴答声 (Stopwatch.EllapsedTicks),下一次运行在 300。它似乎是第一次进行某种编译...
- 有什么方法可以不在运行时编译它,所以它第一次运行时会像下一次一样全速运行?
- 有没有办法进一步优化这段代码?
完整代码(包括测量方法)
using System;
using System.Diagnostics;
using System.Linq;
public static class StopwatchExtender
{
public static void Timer(this Stopwatch sw, Action x, int iterations, string name)
{
sw.Start();
for (int i = 0; i < iterations; ++i)
{
x();
}
sw.Stop();
Console.WriteLine("Name: {0}\nTicks: {1}\n", name, sw.ElapsedTicks);
sw.Reset();
}
}
public static class StringExtender
{
public static string OP(this string str, double preserve)
{
return String.Join(" ",
str.Split(' ')
.Select(x => (x.Count(y => y.ToString() == y.ToString().ToUpper()) / (double)x.Length * 100) > preserve ? x.ToLower() : x)
.Select(x =>
String.Join(String.Empty,
x.Select((y, z) => z == 0 ? y.ToString().ToUpper() : y.ToString()).ToArray()
)
).ToArray()
);
}
public static string A01(this string str, double preserve)
{
return string.Join(" ",
str.Split(' ')
.Select(s => char.ToUpper(s[0]) + ((s.Count(c => char.IsUpper(c)) / (double)s.Length * 100) > preserve ? s.Substring(1).ToLower() : s.Substring(1)))
.ToArray()
);
}
}
public class Program
{
static void Main()
{
var sw = new Stopwatch();
var str = "STACKOVERflow is a quesTions and ANSwers weBSITE";
sw.Timer(() =>
{
str.OP(60);
str.A01(60);
}, 1, "Starup takes more time");
sw.Timer(() =>
{
str.OP(60);
}, 1000000, "OP solution");
sw.Timer(() =>
{
str.A01(60);
}, 1000000, "LukeH's answer");
Console.ReadLine();
}
}
结果
【问题讨论】:
-
如果只运行一次迭代,您将无法获得准确的计时。您应该运行它数万或数百万次。
标签: c# linq optimization