Re: Initializing Variables
On 5/26/2010 3:06 PM, Tom Anderson wrote:
On Tue, 25 May 2010, Lew wrote:
Arne Vajh?j wrote:
I strongly favor readability here. The extra overhead of something
getting initialized twice should be minimal or zero if the JIT
compiler optimizes it away.
Lew wrote:
Minimal, perhaps, but the system is not permitted to optimize away
member initialization.
Arne Vajh?j wrote:
What would prevent the JIT compiler from optimizing the setting of
an int to zero twice to only doing it once?
Lew wrote:
The JLS, section 12.5, "Creation of New Class Instances":
"In some early implementations, the compiler incorrectly omitted the
code to initialize a field if the field initializer expression was a
constant expression whose value was equal to the default initialization
value for its type."
Arne Vajh?j wrote:
But isn't that talking about javac and not JIT?
Not as I read it, but maybe it is.
Regardless, JIT requires multiple executions (by default 10,000 IIRC)
before it decides to optimize something. By definition, initialization
code is run once.
Um, once per instance. If it's an instance initializer. Which is what i
thought we were talking about here. That could easily be run 10 000
times in a single program.
Regardless, as you pointed out and I reiterated, the performance
impact is not enough to trump issues of readability or
self-documentation. Nor is it required to initialize member variables
to their default values.
I admit it's possible that I read this wrong, but I think not.
I don't see how a statement like that is even meaningful when applied to
a JVM. You can require that a JVM behaves *as if* it does or doesn't do
something, defined in terms of some model of what the JVM is doing, but
as long as it does, it can do it however it likes. I don't see how rules
to the contrary would be useful or even possible to judge compliance to.
A suppressed initialization can be observed:
class Super {
Super() {
evilCode();
}
void evilCode() { }
}
class Sub extends Super {
int value = 0; // suppressible?
Sub() {
System.out.println("value = " + value);
}
void evilCode() {
value = 42;
}
public void main(String[] unused) {
new Sub();
}
}
Yes, this is evil code that merits severe chastisement of its author,
but despite its sins it is perfectly legal Java -- and the required
output is "value = 0". If the initialization were suppressed, the
output would be "value = 42" -- and that would (was?) wrong.
--
Eric Sosman
esosman@ieee-dot-org.invalid