Android Program Performance Design Best Practices

Source: Internet
Author: User
Tags integer division

Android apps should be fast and more precise should be efficient. That means limited computing power and data storage in a mobile device environment, a small screen, and a limited battery life to be more efficient. This blog post will show you the best practices for performance.
1. Avoid creating objectsobject creation is much more expensive in android than it is in Java. Try to avoid creating an object, more objects mean more garbage collection, more garbage collection means that users will feel a little "small card". In general, avoid creating ephemeral temporary variables as much as possible, and fewer object creation means less garbage collection, which will improve the user experience. If you can create a "pool" to manage objects, that's the best.
2. Peel off the blocking operation from the UI threaduse Asynctask, Thread, Intentservice, or simple back-office service to do a big, expensive operation. Using loaders to simplify management for a long time loading the state of the data is like a pointer. If an operation consumes time and resources, it is placed asynchronously in another process so that your program can continue to respond and the user can do the same.
3. Using the native methodIn the same Java loop, C + + code can be 10 to 100 times times faster.
4. Implementation is better than interfaceassuming you have a HashMap object, you can use a generic map to declare this hashmap:
Map myMap1 = new HashMap (); HashMap myMap2 = new HashMap ();

Which one is better? The traditional view is that you should use map because it allows you to change the underlying implementation of the map interface as long as it is implemented. Traditional ideas are correct for routine programming, but not so good for embedded systems. Invoking a method that refers to an interface takes twice times more time to invoke than a reference to a fixed implementation. If you hashmap can handle what you are going to do, then using a map to assert it is worthless. Let the IDE help you refactor your code, and even if you don't have a clue about the code, using a map is worthless. (Of course, the public API may be different: a good API definitely trumps small performance issues)
5. Static method is betterIf your method does not need to access the variable of an object, then change your method to static. The call will be much faster because it will not need to go through virtual method table. This is also a good practice because you can tell the method that the signature does not change the state of the object when the method is called.
6. Avoid the use of internal getters/settersin languages like C + +, it is common to see getters (such as I=getcount ()) Instead of direct access variables (i=mcount). This is a good habit, because the compiler uses inline access, and you can modify the code at any time if you are constraining or debugging relative fields. In Android, this is a bad idea. The invocation of a virtual function is expensive, far exceeding the variable's access. If it is a class, you should directly access the variable, if it is a public interface, or try to follow the practice of object-oriented programming to use Getters/setters.
7. Constant declaration FinalConsider the following variable declaration:
static int intval = 42;static String strval = "Hello, world!";

The compiler generates a constructor for a class called <clinit&gt, which is triggered when the class is first used. The method saves 42 to Intval and gets a reference from the string table to Strval. When these values are referenced, they will be able to find them when they visit.
We can use the final keyword to improve performance:
static final int intval = 42;static final String strval = "Hello, world!";

The <clinit> method is no longer required for class files because constants are converted to virtual machines for processing. When the code accesses the intval, it can get 42 directly, and the cost of accessing strval is relatively small.
Declaring a class or method final does not gain performance benefits, and is not enough to have other effects. For example, if you do not want subclasses to override getter methods, you can declare final.
You can also make a local variable final. However, this will not have any performance benefits. For local variables, using final only makes the semantics of the code clearer (or you can have anonymous classes access that variable).
8. Use enhanced for loops with careThe For loop (or For-each loop) that enhances the row can be used on any set that implements the Iterable interface. For these objects, iterator calls the Hasnext () and next () interfaces to create, and for ArrayList, you'd better avoid this way, but for other kinds of collections, the enhanced for loop and the explicit use of iterative loops are similar.
The following code shows the enhanced for loop:
public class Foo {    int msplat;    Static Foo marray[] = new foo[27];    public static void Zero () {        int sum = 0;        for (int i = 0; i < marray.length; i++) {            sum + = Marray[i].msplat;        }    }    public static void One () {        int sum = 0;        foo[] LocalArray = Marray;        int len = localarray.length;        for (int i = 0; i < len; i++) {            sum + = Localarray[i].msplat;        }    }    public static void () {        int sum = 0;        for (Foo a:marray) {            sum + = A.msplat;        }}    }

Zero () retrieves the static variable two times, and each loop gets the length of the array.
One () puts everything in a temporary variable, avoiding the search.
Both () uses the 1.5 version of Java's enhanced for loop, which generates code from the compiler, copies array references and arrays of length to local variables, and produces a good access array scheme that generates an additional locally loaded store (which holds a object), which is a little slower than one ().
The summary is that the enhanced for loop has a better semantics and code structure, but it should be used with caution because there may be additional overhead for creating objects.
9. Avoid enumsEnumeration is very convenient, but unfortunately the size of his speed is painful. For example:
public class Foo {public   enum shrubbery {GROUND, crawling, hanging}}

will be compiled into a 900byte. class file (Foo$shrubbery.class). When used for the first time, the class invokes the initialization function <init> to create an object for each enumerated value. Each object has its own static variables, and all are stored in an array (a static variable called "$VALUES"). So much code, just for three integers.
The following sentence code:
Shrubbery shrub = shrubbery.ground;

The lookup of a static variable. If "GROUND" is a static int constant, the compiler considers it as a known constant and uses inline.
On the other side, you'll certainly get a lot of good APIs and compile-time checks from enumerated types. So, it's usually a tradeoff: you should try to use the enumeration type in all public APIs, but try to avoid it when performance is important.
In some environments, it is useful to obtain the values of an enum through the ordinal () method, such as:
for (int n = 0, n < list.size (); n++) {    if (list.items[n].e = = myenum.val_x)       //do stuff 1    else if (list.it EMS[N].E = = myenum.val_y)       //Do stuff 2}

And then:
int valx = MyEnum.VAL_X.ordinal (); int valy = MyEnum.VAL_Y.ordinal (); int count = List.size (); MyItem items = List.items (); for (int  n = 0; n < count; n++) {     int  valitem = items[n].e.ordinal ();     if (Valitem = = valx)       //do stuff 1     else if (Valitem = = valy)       //Do stuff 2}

In some cases, this will be faster, although there is no guarantee.

10. Use package access to internal classesConsider the following class definition:
public class Foo {    private int mvalue;    public void Run () {        Inner in = new Inner ();        Mvalue =;        In.stuff ();    }    private void Dostuff (int value) {        System.out.println ("value is" + value);    }    Private class Inner {        void stuff () {            Foo.this.doStuff (Foo.this.mValue);}}    }

Key things: We define an inner class (Foo$inner) that accesses private methods and private instances of external classes directly. This is legal, and the code prints out the "Value is 27" we expected.
The problem is that Foo$inner is technically a completely independent class. It is illegal to access the private members of Foo directly. To compensate for this problem, the compiler generates the following method:
/*package*/static int foo.access$100 (foo foo) {    return foo.mvalue;} /*package*/static void foo.access$200 (foo foo, int value) {    Foo.dostuff (value);}

The inner class code calls the method to access the external mvalue or call the external Dostuff method. This means that the real case of the above code is that you are accessing the code through the accessors rather than through the direct access. We've discussed it before. Using accessors is slower than accessing variables directly, so this is a "stealth" performance impact of a particular language habit.


We can avoid this problem by declaring the package access space rather than private access to the space. This will run faster and avoid the overhead generated by the method. (Unfortunately, this may allow other packages under the same package to have direct access to the variable, which violates the object-oriented design idea.) Again, if you're going to design a public API, you need to think about it a little bit. )
11. Avoid floatalmost all game developers will try to use integer arithmetic before the Pentium CPU is released. The Pentium CPU sets the floating-point coprocessor as a built-in feature. by crossing integers and floating-point operations, the game is faster than the previous pure integer operation. The common practice of desktop programs is to use float randomly.
Unfortunately, embedded processors typically do not have floating-point support, so all float and double operations are expensive. some basic floating-point operations can be done in the order of one millisecond.
Similarly, even integers, some chips support multiplication, but lack division. In this case, when the software performs integer division and modulus manipulation, think about if you design a hash table or do a lot of math.
12. Some simple performance figures to illustrate some of our ideas, we have listed approximate uptime for some of the basic behaviors . Note that these values should not be treated as absolute numbers: they are a combination of CPU and clock time, and improvements to the system will change. It is worth noting that these values are relative to each other--for example, adding a member variable currently takes approximately four times times the time to add a local variable .

Action Time
ADD a local variable 1
ADD a member variable 4
Call String.Length () 5
Call empty static native method 5
Call Empty static method 12
Call Empty virtual method 12.5
Call Empty interface method 15
Call Iterator:next () on a HashMap 165
Call put () on a HashMap 600
Inflate 1 View from XML 22,000
Inflate 1 linearlayout containing 1 TextView 25,000
Inflate 1 LinearLayout containing 6 View objects 100,000
Inflate 1 LinearLayout containing 6 TextView objects 135,000
Launch an empty activity 3,000,000

13. SummaryThe best way to write good, effective code is to understand what your code is doing.If you really want to access the enhanced for loop on the list by using an iterator, make it a deliberate choice, not a side effect. As the saying goes! Knowing what you're introducing and inserting some of your favorite things together is also possible, but you have to think carefully about what your code is doing and then find the opportunity to speed it up.

Android Program Performance Design Best Practices

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.