Saturday, November 1, 2014

Reducing memory consumption (Part 1)

Recently our app faced lot of issues because of huge memory consumption. We resolved these issues using following techniques:
1. Reducing font instances
2. Making use of weak references
3. Making handlers static and final

In this post we will see first approach. Second approach will be covered in next post.
1. Reducing font instances
We used to have a custom text view. This text view uses a font provided by application. Code below shows how it used to load.

public boolean setCustomFont(Context ctx, String asset) {
    Typeface tf = null;
    try {
        tf = Typeface.createFromAsset(ctx.getAssets(), "fonts/" + asset.trim());
    } catch (Exception e) {
        Log.e(TAG, "Could not get typeface: " + e.getMessage() + "\n value of asset string " + asset);
        return false;
    }

    setTypeface(tf);
    return true;
}

After using memory profiling tool of android, we came to know that each time this activity is opened memory usage increases. This tool shown the resource held as well.
adb shell dumpsys meminfo com.example.prj
Next step was to reduce the repeated loading of font.
private static Typeface typeFace = null;
public static Typeface getTypeFace(Context ctx, String asset) {
    if (typeFace == null)
        typeFace = Typeface.createFromAsset(ctx.getAssets(), "fonts/" + asset.trim());
    return typeFace;
}
Code above makes the object of type face only once. If it already exists it won't be created again and old object will be used. Before making this change, whenever activity using this TextView was opened, it used to increase memory consumption by 4-5Mb. The size of font file was 0.5 Mb and it was getting loaded 8-10 times on this activity. After making this change, font is loaded only once and takes about 0.5Mb memory.

No comments:

Post a Comment

Android aar deployment in Maven - 2022

Introduction If you are working on android library project, you might be wondering how to publish it on Maven like this . Earl...