是否有快速的替代方法,下面的代码:性能上的文本数据文件
bool isAlphabeticOnly(String strin)
{
foreach (char c in strin)
{
if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z'))
return false;
}
return true;
}
在此先感谢。
是否有快速的替代方法,下面的代码:性能上的文本数据文件
bool isAlphabeticOnly(String strin)
{
foreach (char c in strin)
{
if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z'))
return false;
}
return true;
}
在此先感谢。
好了,这是实现更快一点(但的可读性)
bool isAlphabeticOnly(String strin) {
// comparison with 0 - "i >= 0" - is faster than with strin.Length
for (int i = strin.Length - 1; i >= 0; --i) {
char c = strin[i];
if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z'))
return false;
}
return true;
}
在我的工作站(.NET 4.5,IA64,酷睿i5 3.2GHz的)的平均时间是
Initial 2100 ms
This 1600 ms
测量
// Yes, very long string
String test = new String('p', 100000000) + new String('Q', 100000000);
Stopwatch sw = new Stopwatch();
sw.Start();
isAlphabeticOnly(test);
sw.Stop();
但是,如果您遇到性能问题,这不是isAlphabeticOnly
你应该解决它。
我只能用猫进行测试 - 你需要把所有的字母
不知道这是快,但值得测试
HashSet<char> hsAz = new HashSet<char> { 'a', 't', 'C' };
bool isAlphabeticOnlyHash(String strin)
{
for (int i = strin.Length - 1; i >= 0; --i)
{
if (!hsAz.Contains(strin[i]))
return false;
}
return true;
}
请提供您的基准测试代码,使人们可以测试对你自己的其他建议。 – Heinzi
可能不会显着加快。 - 你短路,正在做快速比较。你确定你的逻辑是正确的吗? –
此外,这是你的应用程序的瓶颈?为什么当你的应用中可能有其他部分可以做得更快时,你担心它的性能? –