问题描述:

For an android application, I am using a logging function which looks like this -

public static void logData(String str) {

if (BuildConfig.DEBUG) Log.d("MYTAG", str);

}

Here, BuildConfig.DEBUG is a static variable which sets to true when compiling the code for debug mode and to false while compiling for release.

I know if I use if(BuildConfig.DEBUG) Log.d("MYTAG", msg); anywhere in my code directly, the compiler would optimize and strip the call completely in release mode.

I would like to know if a function like logData which depends entirely on a single static variable would also get optimized and it's calls removed completely by the compiler. Or would the compiler only make logData to be an empty function and keep all the calls?

网友答案:

No, the compiler won't remove the calls to your logging method though the if block inside would get optimized.

This is called the wrapper approach to logging and its biggest drawback is that any arguments passed are still allocated memory, and in addition to that, any String processing that you do, like,

LogHelper.logData("varName is " + varName);

would incur a slight performance hit as a StringBuilder is still created although the arguments are never actually used for logging.


Optimizations are mostly dependent on the target JVM implementation because it's not the javac compiler that optimizes most of your code but the JIT compiler that translates the byte code to machine code.

That's because it has access to run time stats, which classes are loading or not, and even knows the actual target platform which javac doesn't. But, in the logging case, since BuildConfig.DEBUG is a static final constant, javac can safely optimize out the if block.

To check compile-time optimizations you can use javap disassmebler or any Java de-compiler to look at the generated byte code. For runtime optimizations, you can take a look at this whitepaper The Java HotSpot Performance Engine Architecture from Oracle, especially, Chapter 3. The Java HotSpot Compilers.

网友答案:

i think if BuildConfig.DEBUG defined as final static, it is optimized as the declared value. static is not optimized.

相关阅读:
Top