小编mim*_*o31的帖子

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

我有这样的方法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每次只使用一个实例.

java string performance

3
推荐指数
1
解决办法
70
查看次数

标签 统计

java ×1

performance ×1

string ×1