简体   繁体   中英

How do i prove programatically if a String was initialized?

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.

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.

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.

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.

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 ();
      }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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