An efficient way to put debug / log statements in code is therefore they do not affect runtime

In C-derived languages, it is possible to have conditional code for debugging and runtime. Thus, there is no overhead at runtime.

How can I do this using Java / Android and Log.i statements? If I just use the global boolean debugOn , which explicitly leaves redundant checks at runtime.

What is the best approach for conditional logical operators ?

Many thanks

EDIT:

Since there are quite a few comments following the accepted answer, I post my output here.

 private static final boolean DEBUG = true; if (DEBUG) Log.i("xxx",this.getClass().getName()+ "->" + Thread.currentThread().getStackTrace()[2].getMethodName() ); 

... as in xCode :)

+7
source share
3 answers

The Android build system started providing the BuildConfig.DEBUG constant some time ago, so I suggest using it and writing code like this:

 if (BuildConfig.DEBUG) Log.i(TAG, "Message"); 

No redundant checks will be done as this is a constant. This code will be optimized even by the compiler, but you also have ProGuard. Even if on-site inspections, any potential performance impact should be negligible.

This approach had one drawback that you had to edit this constant yourself, either manually or using a custom rule in the assembly file. Now, however, this is automatically handled by the build system, so you don't have to do anything yourself.

+17
source

Create your own log class by expanding the log class by creating a debugLevel static variable in it, create your own methods and labels, such as INFO, DEBUG, etc.

now the value of the static varable debugLevel will change, affecting the whole application.

therefore there is no need to (debug) everywhere.

+2
source

There is no C-like conditional compilation in Java unless you implement it yourself. (It’s not all that complicated, but IMO it’s not worth the problem.)

Your options are pretty limited. The best you can do is wrap the expensive logging statements in isLoggable .

 if (Log.isLoggable(tag, Log.DEBUG)) { Log.d(tag, expensiveStringGeneration()); } 

For short magazine operators, this is more noise than it costs.

Editing Malcolm may be correct (although I still won't worry, in all likelihood.)

Edit Comparison with static DEBUG is still in byte code; ProGuard should delete an unnecessary branch. Without ProGuard, this will be before the JIT or compiler implementation.

+1
source

All Articles