Reputation: 23443
Though the logging level is set to INFO, and that at runtime the condition will never be satisfied, how am i able to prove programatically if "Hi
" will not be initialized?
if(log.isDebug()){
log.debug("Hi");
}
What i mean is, since the logging level is INFO, the logger would not have a chance to print the message "Hi", my concern is, how can i find out if the JRE or JDK will / will not take a step to prepare "Hi" even through the condition is not satisfied.
Upvotes: 0
Views: 108
Reputation: 47739
Dump the bytecodes. There will be an "ldc" opcode for the String constant. The first time that opcode is executed is when the actual String will be created. The String will then be cached in the constant pool for reuse on subsequent calls/iterations. If the "ldc" never executes the String is not created.
Upvotes: 4
Reputation: 477
I think of the string literal "Hi" is initialised in heap memory readonly
you can do a method like this and calculate memory delta :
if(log.isDebug()){
log.debug("literal");
log.debug(memoryUsed());
log.debug("Hi");
log.debug(memoryUsed());
log.debug("initialising");
log.debug(memoryUsed());
string x = "Hi"
log.debug(x);
log.debug(memoryUsed());
}
static long memoryUsed()
{
return runtime.totalMemory () - runtime.freeMemory ();
}
Upvotes: 0
Reputation: 234847
The literal String "Hi" is part of the class definition. Unless the compiler can determine that the body of the if
is dead code and the literal is not needed, then when the class loader loads the class it will load the literal value. Since it is a compile-time constant, it will also be automatically interned.
The compiler cannot know what the behavior of log.isDebug()
will be when the class is loaded into some unknown execution environment. For all it knows, the logger class definition may be changed so that isDebug()
returns true
regardless of the value set for the logging level.
Upvotes: 3
Reputation: 34573
There's nothing needing to be "initialized" in this code; the string literal "Hi" will be placed into your .class
file by the compiler, so it'll be available for use at runtime regardless of whether it's ever actually used.
Upvotes: 0