【发布时间】:2017-02-14 09:33:15
【问题描述】:
如何减少 for 循环所花费的时间,如果可能的话,使用 replaceAll(,) 方法删除 for 循环:
String extractText(String s) throws IOException
{
String html = fj.toHtmlString(s); //extracted html source code from wikipedia
String filtered_text="";
System.out.println("extracted \n\n");
String []html_text = html.split("\n");
long start = System.currentTimeMillis();
for(String h:html_text)
{ //System.out.println("ky4"+h);
if(Pattern.compile("</strong>", Pattern.CASE_INSENSITIVE + Pattern.LITERAL).matcher(h).find())
{
}
else if(Pattern.compile("<strong", Pattern.CASE_INSENSITIVE + Pattern.LITERAL).matcher(h).find())
{
}
else
{
filtered_text += h;
filtered_text += "\n";
}
}
long end = System.currentTimeMillis();
System.out.println("loop end in "+(end-start)/1000+" seconds"+" or "+(end-start)+" miliseconds");//System.out.println(++i2+" th loop end in "+(end-start)/1000+" seconds");
return filtered_text;
}
【问题讨论】:
-
是代码审查反馈吗?
-
您在 for 循环中创建了不必要的对象。
-
所以我要求尽可能使用 replaceAll() 方法替换整个 for 循环代码,我该怎么办?
-
如果我从这个“en.wikipedia.org/wiki/Varanasi”URL 中提取 html 源代码,for 循环需要大约 6 秒来计算逻辑