Does java optimize string literal toLowerCase()?

青春壹個敷衍的年華 提交于 2019-12-01 05:03:20

问题


Does java optimize operations with string literals? For example, does

"literal".toLowerCase()

always create a new string instance?


回答1:


toLowerCase() calls toLowerCase(Locale.getDefault()).

Looking at the implementation you'll see that the original String is returned if no characters need to be changed:

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
    }
    ...
}



回答2:


First of, I think that is unspecified, so the behavior might differ between JDKs.

However, in my Oracle JDK 1.8.0_131, when I look at the source code of String.toLowerCase(Locale), I see that there is a check that returns the string itself, if no characters need to be changed.

/* 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
....


来源:https://stackoverflow.com/questions/47012268/does-java-optimize-string-literal-tolowercase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!