Home > Articles > Mobile Application Development & Programming

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020