【发布时间】:2012-05-18 03:54:06
【问题描述】:
我有一个很长的字符串(60MB),我需要在其中找到有多少对“”。
我首先尝试了自己的方式:
char pre = '!';
int match1 = 0;
for (int j = 0; j < html.Length; j++)
{
char c = html[j];
if (pre == '<' && c == '>') //find a match
{
pre = '!';
match1++;
}
else if (pre == '!' && c == '<')
pre = '<';
}
上面的代码在我的字符串上运行了大约 1000 毫秒。
然后我尝试使用string.IndexOf
int match2 = 0;
int index = -1;
do
{
index = html.IndexOf('<', index + 1);
if (index != -1) // find a match
{
index = html.IndexOf('>', index + 1);
if (index != -1)
match2++;
}
} while (index != -1);
上面的代码只运行了大约 150 毫秒。
我想知道是什么魔力让string.IndexOf 运行这么快?
谁能启发我?
编辑
好的,根据@BrokenGlass 的回答。我修改了我的代码,他们不检查配对,而是检查字符串中有多少个“
for (int j = 0; j < html.Length; j++)
{
char c = html[j];
if (c == '>')
{
match1++;
}
}
上面的代码运行了大约 760 毫秒。
使用IndexOf
int index = -1;
do
{
index = html.IndexOf('<', index + 1);
if (index != -1)
{
match2++;
}
} while (index != -1);
上面的代码运行了大约 132 毫秒。 仍然非常非常快。
编辑 2
阅读@Jeffrey Sax 的评论后,我意识到我是在 VS 中以 Debug 模式运行的。
然后我在发布模式下构建并运行,好的,IndexOf 仍然更快,但不再那么快了。
结果如下:
对于配对计数:207ms VS 144ms
对于正常的一个字符数:141ms VS 111ms。
我自己的代码的性能确实得到了改善。
经验教训:当您进行基准测试时,请在发布模式下进行!
【问题讨论】:
-
您是否在测试时启用了优化?
-
你看过
string.IndexOf在幕后做了什么吗? -
@MartinLiversage 如何启用优化?
-
@zimdanen 不,这就是我真正要问的
-
尽量不要使用html.length,尝试
int len =html.length;,然后在for循环中使用len。