简体   繁体   English

非最终静态字符串是否比静态最终字符串更有效?

[英]Are non-final static strings more efficient than static final strings?

I just read an article in the BlackBerry docs about writing efficient code in J2ME . 我刚刚读了BlackBerry文档中有关在J2ME中编写高效代码的文章。

In that article there is a section that advises you to "use static variables for Strings." 在该文章中,有一节建议您“对字符串使用静态变量”。 The reasoning is that, since the compiler inlines static final references as string literals, it's better to leave it non-final (I guess the assumption is that retrieving a static reference is cheaper than retrieving from the string pool?). 原因是,由于编译器将static final引用内联为字符串文字,因此最好将其保留为非最终形式(我猜这是假设检索静态引用比从字符串池检索便宜吗?)。

Is this true for all JVMs?? 所有的JVM都是这样吗? My boss at my last job pounded it into our heads that we should always, always use static final for our constants. 我的上司在上一份工作中动摇了我们的头脑,我们应该始终, 始终对常量使用static final We were doing embedded programming in Java, so he was a real stickler for performance (although I'm not sure in this case whether he was more concerned with memory or speed). 我们当时正在用Java进行嵌入式编程,因此他是提高性能的坚强后盾(尽管在这种情况下我不确定他是否更关注内存或速度)。 My boss has been doing Java for years and really knows his stuff, so I took his advice; 我的老板已经使用Java多年了,并且真的很了解他的知识,所以我接受了他的建议。 now I'm getting contradictory advice! 现在我得到矛盾的建议!

So which one is really better? 那么哪个真的更好? You can answer from either a memory conservation perspective or a speed perspective, and for either J2ME or J2SE. 您可以从内存保护角度或速度角度以及J2ME或J2SE回答。

In general, they should be the same. 通常,它们应该相同。 (With the same defined as close enough that it will never ever matter) (具有相同的定义,即足够接近以至于永远都不会影响)

I would very strongly argue that you should encode your intent (ie having the static vs non-static-ness defined by whether this is a class constant versus an instance constant) rather than some arbitrary "performance enhancement" 我会极力主张您应该对意图进行编码(即,根据这是常量还是实例常量来定义静态与非静态),而不是任意的“性能增强”

If you find that this is a significant performance problem (and only AFTER you measure it!), I would classify it as a compiler / JVM defect and put the workaround (Swapping its static-ness) in place, with a comment indicating why. 如果您发现这是一个严重的性能问题(并且只有在对其进行测量之后才可以!),我将其归类为编译器/ JVM缺陷,并将解决方法(交换其静态性)放在适当的位置,并用注释说明原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM