Java 如果我多次使用字符串,将其声明为final是否明智?
我有一个方法Java 如果我多次使用字符串,将其声明为final是否明智?,java,string,performance,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 } public
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
}
public static final String s = "myString";
public void repeatedMethod() {
anotherMethod(s);
}
我多次调用repeatedMethod
我想问,在该方法之外声明myString
为static final
是否明智,如下所示:
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
}
public static final String s = "myString";
public void repeatedMethod() {
anotherMethod(s);
}
我认为当我执行anotherMethod(“myString”)
时,就会创建一个String
的新实例。由于我做了很多次,所以创建了许多String
的实例
因此,最好在
repeatedMethod
之外只创建一个字符串的实例,并且每次只使用该实例。您所做的是正确的,但原因是错误的
执行anotherMethod(“myString”)
时,实际上不会创建String
的新实例:它可能会重用字符串常量池中的字符串(请参阅)
但是,将公共字符串值分解为常量(即作为私有静态final
)是一种很好的做法:如果该常量需要更改,您只需要在源代码的一个位置更改它(例如,如果明天,“myString”
需要变成“myString2”
,您只需要进行一次修改)相同文本的字符串文本是相同的,不会像您担心的那样创建过多的对象
但最好将该字符串文字放在静态最终变量(常量)中,并使用描述性名称记录该字符串的用途。通常建议将字符串文字提取到具有良好名称的常量
当同一个字符串文字出现在代码中的多个位置(“神奇字符串”)时尤其如此,在这种情况下,强烈建议提取到常量。不,您不需要这样做,JVM中有一个“常量池”,用于每个内联字符串(例如:“myString”),它将被隐式地视为常量变量,并且每个相同的内联字符串将只放入常量池一次
比如说,
String i="test",j="test";
常量池中只有一个常量变量“test”的实例
也指
在担心性能之前,先进行优化以澄清问题。字符串文本只创建一次,永远(除非卸载该文本),在这种情况下,性能不仅不那么重要,而且不重要
您应该定义一个常量,而不是重复相同的字符串,以明确这些字符串不是相同的,而是必须相同。如果以后试图维护代码的人不得不修改一个字符串,这是否意味着他们应该全部更改
顺便说一句,当你为了清晰而优化时,你也经常为了性能而优化。JIT寻找常见的模式,如果您试图智能化优化器,则更有可能将其混淆,从而导致不太理想的代码