Does java optimize string literal toLowerCase()?

前端 未结 2 1684
遥遥无期
遥遥无期 2021-01-13 19:40

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

\"literal\".toLowerCase()

always create a new string instance?

2条回答
  •  青春惊慌失措
    2021-01-13 20:17

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

提交回复
热议问题