Home > Articles > Mobile Application Development & Programming

  • Print
  • + Share This
This chapter is from the book

Additional Performance Improvements

There are many causes of performance issues, but they are nearly always related to doing too much work on the UI thread. Sometimes you can affect these issues directly (like moving the loading of images to a background thread) and other times you have to be less direct (like maintaining a reference to an object you don’t need to avoid garbage collection during an animation). Whether you have to be direct or not, knowing additional techniques to improve performance is always beneficial.

Controlling Garbage Collection

Garbage collection is one of those things that you can simultaneously love and hate. It’s great because it lets you focus on the fun part of developing an app rather than worrying about tedious tasks like reference counting. It’s horrible because it slows down your app when it happens. Although Android has had concurrent garbage collection for years now and its introduction helped a huge amount, garbage collection can still cause jank. Remember, you have just 16 milliseconds for each frame, so the garbage collector taking just 4 milliseconds is effectively taking 25% of your time for that frame.

Although you can’t do much to control the garbage collector directly other than just triggering a collection, you can adjust the way you code your app to decrease the work it does or even simply change the timing. In particular, you should be conscious of where you are allocating memory and where you are releasing it. Every time you allocate memory, such as declaring an object or array, you are asking the system for a consecutive chunk of free memory. The fact that it’s consecutive is important because that means even if you have 10mb free, you could ask for 500kb and still incur the cost of the VM reorganizing the memory if there isn’t enough consecutive free memory available. Even if the virtual machine doesn’t have to clear out memory, just moving chunks of memory around to make a large, consecutive section takes time. On the other side of that, every time you get rid of a reference to an object or an array and that was the last reference to that object or array, there is a chance the garbage collector will run. Halfway done with that animation and now you don’t need those giant bitmaps? Removing your reference could cause the animation to pause or skip frames.

In general, you don’t want to allocate or release memory in any method that is already potentially slow or gets called many times in succession. For instance, be careful in the onDraw and onLayout methods of View (both are covered in Chapter 13, “Developing Fully Custom Views”), getView of Adapter implementations, and any methods you trigger during animations. If you have to allocate objects, consider whether it’s possible to keep them around or reuse them (such as in an object pool).

View Holder Pattern

ListView and other AbsListView implementations are excellent ways to effectively display a subset of a larger data set. They effectively reuse views to limit garbage collection and keep everything smooth, but it’s still easy to run into problems. One of the most common methods to use within a getView call of an adapter is findViewById. For example, look at Listing 10.7 that shows a simple getView implementation.

Listing 10.7 An Example getView Method

public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        convertView = mLayoutInflater.inflate(R.layout.list_item, parent, false);
    }

    ListItem listItem = getItem(position);
    ImageView imageView = (ImageView) convertView.findViewById(R.id.imageView);
    Drawable drawable = mContext.getDrawable(R.drawable.person);
    drawable.setTintMode(PorterDuff.Mode.SRC_ATOP);
    drawable.setTint(listItem.getColor());
    imageView.setImageDrawable(drawable);

    TextView textView = (TextView) convertView.findViewById(R.id.count);

    textView.setText(listItem.getCount());
    textView = (TextView) convertView.findViewById(R.id.title);
    textView.setText(listItem.getTitle());
    textView = (TextView) convertView.findViewById(R.id.subtitle);
    textView.setText(listItem.getSubtitle());

    return convertView;
}

Each getView call traverses the view to find the views that need to be updated. In this case, there are four separate findViewById calls. Each call will first check the convertView ID, then the children one at a time until a match is found. If this example has just the convertView plus the four views that are searched for, the first call will check two views to get the match, the next three, and so on. This leads to 14 view lookups in this simple case! The more complex the view, the longer it takes to traverse the hierarchy and find the views you are looking for.

The ideal solution would be to only have to find the views one time and then just retain the references, and that’s what the view holder pattern does. Because you are reusing views (via the convert view), you have to traverse a finite number of views before you have found every view you care about in the list. By creating a class called ViewHolder that has references to each of the views you care about, you can instantiate that class once per view in the ListView and then reuse that class as much as needed. This class is implemented as a static inner class, so it is really just acting as a container for view references. See Listing 10.8 for a simple example of a class that takes the view and sets all the necessary references.

Listing 10.8 An Example of a ViewHolder Class

private static class ViewHolder {
    /*package*/final ImageView imageView;
    /*package*/final TextView count;
    /*package*/final TextView title;
    /*package*/final TextView subtitle;

    /*package*/ ViewHolder(View v) {
        imageView = (ImageView) v.findViewById(R.id.imageView);
        count = (TextView) v.findViewById(R.id.count);
        title = (TextView) v.findViewById(R.id.title);
        subtitle = (TextView) v.findViewById(R.id.subtitle);
    }
}

Looking back at the getView method, a few minor changes can significantly improve the efficiency. If convertView is null, inflate a new view as we already have and then create a new ViewHolder instance, passing in the view we just created. To keep the ViewHolder with this view, we call the setTag method, which allows us to associate an arbitrary object with any view. If convertView is not null, we simply call getTag and cast the result to the ViewHolder.

Now that we have the ViewHolder, we can just reference the views directly, so the rest of the getView code is not only much simpler than before but also better performing and easier to read. See Listing 10.9 for the updated getView call. Any time you use an adapter and you use the child views in the getView method, you should use this view holder pattern. For example, the ToolArrayAdapter in the woodworking tools app should be updated to use the view holder pattern; give it a try.

Listing 10.9 The getView Method Using a ViewHolder

public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder viewHolder;
    if (convertView == null) {
        convertView = mLayoutInflater.inflate(R.layout.list_item, parent, false);
        viewHolder = new ViewHolder(convertView);
        convertView.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }

    ListItem listItem = getItem(position);
    Drawable drawable = mContext.getDrawable(R.drawable.person);
    drawable.setTintMode(PorterDuff.Mode.SRC_ATOP);
    drawable.setTint(listItem.getColor());
    viewHolder.imageView.setImageDrawable(drawable);

    viewHolder.count.setText(listItem.getCount());
    viewHolder.title.setText(listItem.getTitle());
    viewHolder.subtitle.setText(listItem.getSubtitle());

    return convertView;
}

Eliminating Overdraw

Overdraw is when your app causes pixels to be drawn on top of each other. For example, imagine a typical app with a background, whether plain or an image. Now you put an opaque button on it. First, the device draws the background; then it draws the button. The background under the button was drawn but is never seen, so that processing and data transfer are wasted.

You might wonder how you can actually eliminate overdraw then, and the answer is that you do not need to. You only need to eliminate excessive overdraw. What “excessive” means is different for each device, but the general rule of thumb is that you should not be drawing more than three times the number of pixels on the screen (as detailed in Chapter 7, “Designing the Visuals”). When you go above three times the number of pixels, performance often suffers.

It’s worth noting that some devices are better than others at efficiently avoiding drawing pixels when opaque pixels would be drawn right on top of them. GPUs that use deferred rendering are able to eliminate overdraw in cases where fully opaque pixels are drawn on fully opaque pixels, but not all Android devices have GPUs that use deferred rendering. Further, if pixels have any amount of transparency, that overdraw cannot be eliminated because the pixels have to be combined. That is why designs that contain a significant amount of transparency are inherently more difficult to make smooth and efficient than designs that do not.

Overdraw is easiest to eliminate when you can see it. Android 4.2 and newer offer a developer option to show GPU overdraw by coloring the screen differently based on how many times a pixel has been drawn and redrawn. To enable it, go to the device settings and then Developer options and scroll to the “drawing” section to enable the Show GPU Overdraw option (see Figure 10.7). When this option is checked, apps will be colored to show the amount of overdraw. Current versions of Android don’t require restarting the app, but older versions do.

Figure 10.7

Figure 10.7 The Show GPU Overdraw option in Android’s developer options

First, you should understand what the color tints mean. If there is no tint, there is no overdraw, and this is the ideal situation. A blue tint indicates a single overdraw (meaning the pixel was drawn once and then drawn again), and you can think of it as being “cold” because your device can easily handle a single level of overdraw (so the processor is not overheating). When something is tinted green, it has been overdrawn twice. Light red indicates an overdraw of three times, and dark red indicates an overdraw of four (or more) times (red, hot, bad!).

Large sections of blue are acceptable as long as the whole app is not blue (if it were, that’d suggest you’re drawing the full screen and immediately redrawing it, which is very wasteful). Medium-sized sections of green are okay, but you should avoid having more than half of the screen green. Light red is much worse, but it’s still okay for small areas such as text or a tiny icon. Dark red should make you cry. Well, maybe not cry, but you should definitely fix any dark red. These areas are drawn five times (or more), so just imagine your single device powering five full screens and you should realize how bad this is.

Figure 10.8 shows a very simple design that is just a list of text. Judging by the simple appearance, it looks like the device has to do minimal work to get these pixels on the display; however, we can turn on the overdraw visualization and see how bad things actually are. Figure 10.9 shows the design tinted by the Show GPU Overdraw option. The full source code for this example is in the OverdrawExample project in the chapter10 folder.

Figure 10.8

Figure 10.8 Simple app that shouldn’t require much work by the device

Figure 10.9

Figure 10.9 The same app with overdraw being displayed

First, you should know that the theme your app uses should have a window background. This can be a drawable and it is usually a simple color. Android uses this when your app is first being displayed to immediately show some visual indication of what your app should look like even before the views have been inflated. This makes the device feel more responsive because it can respond to the tap even before you’ve initiated the activity and inflated its views. This window background stays on the screen and everything else is painted on top. That means if you have an activity with a layout that also draws a background, you can very easily draw all pixels on the screen twice and then more times when the views are put on top.

Another common source of overdraw is with items in a ListView. The example is not only drawing a white background with the activity’s base view right on top of the window background, it is drawing a white background for each list item over that, which is entirely unnecessary. By simply eliminating the extra backgrounds, the overdraw visualization (shown in Figure 10.10) is immediately improved.

Figure 10.10

Figure 10.10 Overdraw visualization after eliminating extra backgrounds

Remember that you don’t need to eliminate all overdraw, but you should generally minimize it. You should be conscious of what views are drawing in front of and check the overdraw visualization now and then.

  • + Share This
  • 🔖 Save To Your Account