4

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?

Kirill Kulakov
  • 10,035
  • 9
  • 50
  • 67

2 Answers2

1

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 :)

Community
  • 1
  • 1
Zbigniew Malinowski
  • 1,034
  • 1
  • 9
  • 22
0

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.

Willis
  • 5,308
  • 3
  • 32
  • 61
  • that might be great if you have the same log all over the code, but usually it's dynamically generated (I'll add example to the question) – Kirill Kulakov Feb 02 '15 at 19:27