如果我多次使用它,将String声明为final是否明智?

mim*_*o31 3 java string performance

我有这样的方法repeatedMethod:

public static void repeatedMethod() {
    // something else
    anotherMethod("myString");
    // something else
}

public static void anotherMethod(String str) {
    //something that doesn't change the value of str
}
Run Code Online (Sandbox Code Playgroud)

repeatedMethod多次打电话.

我想问一下myString,static final在这种方法之外声明是否明智是这样的:

public static final String s = "myString";

public void repeatedMethod() {
    anotherMethod(s);
}
Run Code Online (Sandbox Code Playgroud)

我认为,当我这样做时anotherMethod("myString"),String会创建一个新实例.由于我多次这样做,String因此创建了许多实例.

因此,最好只创建一个String外部实例,repeatedMethod每次只使用一个实例.

Tun*_*aki 6

你正在做的是对的,但出于错误的原因.

当你这样做时anotherMethod("myString"),String实际上不会创建新的实例:它可能会重用String常量池中的String(参考这个问题).

然而,保理常见字符串值作为常数(即作为private static final)是一个很好的做法:如果恒曾经需要改变,你只需要改变一个地方的源代码(例如,如果明天,"myString"需要成为"myString2",你只进行一次修改)