参考您的编辑 2,它总是看起来有点不确定,因为它违反了比 OO 更古老的编程正统观念:“结构化编程”(参见http://en.wikipedia.org/wiki/Structured_programming)。它也带有 goto 的味道,所有优秀的程序员都知道,如果他们在代码中加入了 goto,他们需要承认。
可能有人担心它可能会使编译器更难分析函数的控制流,但它是一种通常出于效率原因而使用的工具。例如,Apache 的实现java.lang.String
在这个函数中使用它,至少是为了优化:
/*
* An implementation of a String.indexOf that is supposed to perform
* substantially better than the default algorithm if the "needle" (the
* subString being searched for) is a constant string.
*
* For example, a JIT, upon encountering a call to String.indexOf(String),
* where the needle is a constant string, may compute the values cache, md2
* and lastChar, and change the call to the following method.
*/
@SuppressWarnings("unused")
private static int indexOf(String haystackString, String needleString,
int cache, int md2, char lastChar) {
char[] haystack = haystackString.value;
int haystackOffset = haystackString.offset;
int haystackLength = haystackString.count;
char[] needle = needleString.value;
int needleOffset = needleString.offset;
int needleLength = needleString.count;
int needleLengthMinus1 = needleLength - 1;
int haystackEnd = haystackOffset + haystackLength;
outer_loop: for (int i = haystackOffset + needleLengthMinus1; i < haystackEnd;) {
if (lastChar == haystack[i]) {
for (int j = 0; j < needleLengthMinus1; ++j) {
if (needle[j + needleOffset] != haystack[i + j
- needleLengthMinus1]) {
int skip = 1;
if ((cache & (1 << haystack[i])) == 0) {
skip += j;
}
i += Math.max(md2, skip);
continue outer_loop;
}
}
return i - needleLengthMinus1 - haystackOffset;
}
if ((cache & (1 << haystack[i])) == 0) {
i += needleLengthMinus1;
}
i++;
}
return -1;
}