java是否使用字符串文字优化操作?例如,
"literal".toLowerCase()
总是创建一个新的字符串实例?
答案 0 :(得分:4)
toLowerCase()
来电toLowerCase(Locale.getDefault())
。
查看实现,如果不需要更改任何字符,您将看到返回原始String
:
public String toLowerCase(Locale locale) {
if (locale == null) {
throw new NullPointerException();
}
int firstUpper;
final int len = value.length;
/* Now check if there are any characters that need to be changed. */
scan: {
for (firstUpper = 0 ; firstUpper < len; ) {
char c = value[firstUpper];
if ((c >= Character.MIN_HIGH_SURROGATE)
&& (c <= Character.MAX_HIGH_SURROGATE)) {
int supplChar = codePointAt(firstUpper);
if (supplChar != Character.toLowerCase(supplChar)) {
break scan;
}
firstUpper += Character.charCount(supplChar);
} else {
if (c != Character.toLowerCase(c)) {
break scan;
}
firstUpper++;
}
}
return this; // the original String is returned
}
...
}
答案 1 :(得分:3)
首先,我认为这是未指定的,因此JDK之间的行为可能不同。
但是,在我的Oracle JDK 1.8.0_131中,当我查看String.toLowerCase(Locale)的源代码时,如果不需要更改字符,我会看到有一个检查返回字符串本身。 / p>
/* Now check if there are any characters that need to be changed. */
scan: {
for (firstUpper = 0 ; firstUpper < len; ) {
// Basically
if(characterNeedsToBeChanged) {
break scan;
}
}
return this;
}
...
// Create a new string
....