Kirill Kulakov
Kirill Kulakov

Reputation: 10255

Logcat during production

I used to use my a custom class that is responsible for logging with the following implementation

public class Logger {

     public final static boolean DEBUG = true;

     public static void d(String tag, String msg) {
         if(DEBUG)
             Log.d(tag, msg);
     }

} 

When I release the app I set the flag to false, however I was said that the following method is not that efficient since the Strings are still being allocated and then deallocated in the memory

the logger being used like that:

Logger.d("tag", "message");

or maybe like that, by doing that the StringBuilder will be invoked

Logger.d("tag", "server response: " + response + " timing: " + timing);

Is that true, can't the dalvik/compiler optimize it to prevent such behaviour. and if so, is there something I can do to optimize it other than moving the if outside?

Upvotes: 4

Views: 176

Answers (2)

Zbigniew Malinowski
Zbigniew Malinowski

Reputation: 1074

Try to use Proguard to entirely remove logging from bytecode of your production apk. On debug version just disable "proguarding".

E.g.:

Remove all debug logging calls before publishing: are there tools to do this?

By the way, few unnecesary string concatenations are not good, but usually are not that hard (unless you are doing it many times in the loop), so don't demonize it :)

Upvotes: 1

Willis
Willis

Reputation: 5336

A simple solution would be to just just declare two String variables in your Activity and reuse them whenever you add a log entry like so:

public class YourActivity extends Activity
{
    String tag;
    String message;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        // Rest of Activity

Then whenever you want to add a log entry simply set the tag/message value:

tag = "myTag";
message = "myMessage";
Logger.d(tag, message);

This way your if check remains inside Logger and no additional memory is allocated.

Upvotes: 0

Related Questions