Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Mail Systems
Eclipse Documentation

How To Guides
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Problem Solutions
Privacy Policy




Android Development
Previous Page Home Next Page

Cache Field Lookups

Accessing object fields is much slower than accessing local variables. Instead of writing:

for (int i = 0; i < this.mCount; i++)

You should write:

  int count = this.mCount;
  Item[] items = this.mItems;
  for (int i = 0; i < count; i++)

(We're using an explicit "this" to make it clear that these are member variables.)

A similar guideline is never call a method in the second clause of a "for" statement. For example, the following code will execute the getCount() method once per iteration, which is a huge waste when you could have simply cached the value as an int:

for (int i = 0; i < this.getCount(); i++)

It's also usually a good idea to create a local variable if you're going to be accessing an instance field more than once. For example:

    protected void drawHorizontalScrollBar(Canvas canvas, int width, int height) {
        if (isHorizontalScrollBarEnabled()) {
            int size = mScrollBar.getSize(false);
            if (size <= 0) {
                size = mScrollBarSize;
            mScrollBar.setBounds(0, height - size, width, height);
                    computeHorizontalScrollExtent(), false);

That's four separate lookups of the member field mScrollBar. By caching mScrollBar in a local stack variable, the four member field lookups become four stack variable references, which are much more efficient.

Incidentally, method arguments have the same performance characteristics as local variables.

Android Development
Previous Page Home Next Page

  Published under the terms fo the Apache 2.0 License Design by Interspire