问题描述
我遇到了一个包含多个字符串文字"foo"的类.
I've come across a class that includes multiple uses of a string literal, "foo".
我想知道的是,使用这种方法而不是将String声明为final并将所有文字替换为final变量有什么好处和影响(就对象创建,内存使用和速度而言) ?
What I'd like to know, is what are the benefits and impact (in terms of object creation, memory usage and speed) of using this approach instead of declaring the String as final and replacing all the literals with the final variable?
例如(尽管显然不是真正的单词用法):
For example (although obviously not a real word usage):
private static final String FINAL_STRING = "foo";
public void stringPrinter(){
for(int i=0;i<10;i++){
System.out.println(FINAL_STRING);
}
}
对:
public void stringPrinter(){
for(int i=0;i<10;i++){
System.out.println("foo");
}
}
哪个更可取,为什么(假设字符串值将保持不变)?
Which is preferable and why (assuming the string value will remain constant)?
以上(第二个)示例将导致创建10个String对象,还是让JVM意识到实际上仅使用了一个文字,并创建了一个引用.如果是这样,将String声明为final是否有好处(如第一个示例所示)?
Would the above (second) example result in 10 String objects being created or would the JVM realise that only a single literal is actually used, and create a single reference. If so, is there any advantage for declaring the String as final (as in the first example)?
如果解释后的代码确实用单个引用替换了字符串文字,那么如果相同的文字出现在多个地方,这是否仍然适用:
If the interpreted code does replace the string literal with a single reference, does that still apply if the same literal occurs in more than one place:
public void stringPrinter(){
for(int i=0;i<5;i++){
System.out.println("foo"); // first occurence
System.out.println("foo"); // second occurence
}
}
推荐答案
它们将完全相同.在这两种情况下,文字都是中间值(导致该字符串与所有其他常量/文字共享相同实例的任何编译时常量表达式),并且聪明的编译器+运行时将这两个都简化为最优化的示例应该没有问题.
They will be exactly the same. The literal is interned (any compile time constant expression that results in that string shares the same instance as all other constants/literals) in both cases and a smart compiler+runtime should have no trouble reducing both to the most optimized example.
优势来自可维护性.如果要更改文字,则只需要用一个常量更改一次出现,但是如果它们是内联包含的,则需要搜索和更改每个实例.
The advantage comes more in maintainability. If you want to change the literal, you would need only change one occurrence with a constant but you would need to search and change every instance if they were included inline.
这篇关于使用相同的String文字而不是final变量有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!