使用相同的字符串文字而不是最终变量? [英] Using identical String literals instead of a final variable?

查看:81
本文介绍了使用相同的字符串文字而不是最终变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到过一个包含多个字符串文字用法的类,foo。

I've come across a class that includes multiple uses of a string literal, "foo".

我想知道的是什么使用这种方法的好处和影响(在对象创建,内存使用和速度方面),而不是将String声明为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.

这篇关于使用相同的字符串文字而不是最终变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆