Does java optimize string literal toLowerCase()?

前端 未结 2 1623
遥遥无期
遥遥无期 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:33

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

提交回复
热议问题