Neil Traft
Neil Traft

Reputation: 19726

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.

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?).

Is this true for all JVMs?? My boss at my last job pounded it into our heads that we should always, always use static final for our constants. 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). My boss has been doing Java for years and really knows his stuff, so I took his advice; 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.

Upvotes: 1

Views: 367

Answers (1)

Steven Schlansker
Steven Schlansker

Reputation: 38536

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 (i.e. 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.

Upvotes: 3

Related Questions