此代码比标准 String.toUpperCase() 函数快大约 3 倍:
public static String toUpperString(String pString) {
if (pString != null) {
char[] retChar = pString.toCharArray();
for (int idx = 0; idx < pString.length(); idx++) {
char c = retChar[idx];
if (c >= 'a' && c <= 'z') {
retChar[idx] = (char) (c & -33);
}
}
return new String(retChar);
} else {
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
为什么速度这么快?String.toUpperCase() 还做了哪些其他工作?换句话说,在某些情况下该代码将不起作用吗?
随机长字符串(纯文本)执行 2,000,000 次的基准结果:
toUpperString(String) : 3514.339 ms - 大约 3.5 秒
String.toUpperCase() : 9705.397 ms - 几乎 …