有一种方法可以从文本中搜索子字符串(使用暴力算法,请忽略空指针)
public static int forceSearch(String text, String pattern) {
int patternLength = pattern.length();
int textLength = text.length();
for (int i = 0, n = textLength - patternLength; i <= n; i++) {
int j = 0;
for (; j < patternLength && text.charAt(i + j) == pattern.charAt(j); j++) {
;
}
if (j == patternLength) {
return i;
}
}
return -1;
}
奇怪的是,虽然使用相同的算法,但以下代码更快!!!
public static int forceSearch(String text, String pattern) {
int patternLength = pattern.length();
int textLength = text.length();
char first = pattern.charAt(0);
for (int i = 0, n = textLength - patternLength; i <= n; i++) {
if (text.charAt(i) != first) {
while (++i <= n && text.charAt(i) != first)
;
}
int j = 0;
for (; j < patternLength && text.charAt(i + j) == pattern.charAt(j); j++) {
;
}
if (j == patternLength) {
return i;
}
}
return -1;
}
如果我在JVM上运行,我发现第二段代码明显比第一段快。然而,当我将其编写为C并运行时,这两个函数花费的时间几乎相同。因此,我认为原因是JVM优化了循环代码。
if (text.charAt(i) != first) {
while (++i <= max && text.charAt(i) != first)
;
}
我说的对吗?如果我说的对,我们应该如何使用JVM优化策略来优化我们的代码呢?
希望有人能帮忙,谢谢:)