[Change] the preparation of efficient Android code

sponsored links

Android write efficient code

There is no doubt that devices based on Android platform must be embedded devices. Modern handheld devices is not just a simple phone, it is a small handheld computer, but even the fastest of the most high-end handheld devices far smaller than a medium-performance desktop machine.

This is why the procedure in the preparation of Android moment when consider implementing Di efficiency, these systems Bushixiangxiang in the so fast, Bingju you consider Ta Hai Yao Neng Li battery's life. This means that there is little space left for you to go to waste, so, in the process when you write Android to make your code as possible while optimizing efficiency.

This page describes several Android allows developers to run a more efficient way. Some jump through the following link, you can learn how to make your program run more efficiently


  • Introduction
  • To avoid creating an object
  • Use their own methods
  • Better than the use of virtual interfaces
  • Better than using a static virtual
  • Avoid internal use Setter and Getter
  • Buffer attribute called
  • Final statement of constant
  • Prudent use of enhanced For loop
  • Avoid Enums to avoid the type listed
  • Package through the use of space within the joint class
  • Avoid floating-point type
  • Comparison of some of the standard operation of the time
  • Conclusion


How to determine a system for the irrational, there are two basic principles:

  • Do not do unnecessary things to do.
  • As much as possible to save memory usage.

All of the following methods are based on these two.

Some may think that this page has spent a lot of space to say how "preliminary optimization" (premature optimization). Although sometimes micro-optimization of the development of efficient data structures and algorithms is very difficult, but in the embedded handheld devices, you have no choice above. For example, if the desktop virtual machine migration to your Android system, you will find that you write your program will run out of memory. This will cause the program up and running extremely slow, even without considering the rest of its system of running the program.

This is why the above two principles are so important. Android's success is the development of procedures available to the user experience, user experience, good or bad, however, decided whether the code in your timely response and thus will not make people slow collapse. Because we all procedures to run in the same equipment, so we consider them as a whole. This test driver's license as you need to learn the rules of the road is the same: If the owner to comply with, things will be very smooth; but when you do not comply, you will crash.

Before we discuss substantive issues, there is a brief explanation: Regardless of whether the virtual machine is a Java compiler features all the views presented below are correct. If we have two ways to accomplish the same thing, but foo () to explain the implementation of faster than bar (), then foo () will not build speed than the bar () slow, only by compiling the code allows you to run speed boost is unwise.

As far as possible to create objects (Object)

Object creation is not without cost. Distribution with a thread pool of generational memory management mechanism will reduce the cost of creating temporary objects are not allocated memory does not allocate memory is not as good.

If you are in a cycle of the user interface assigned an object, you have to force the recall of memory, it would appear to make the user experience a little "hiccup" phenomenon.

Therefore, if there is no need you should not create the object instance. Here is a helpful example:

  • When the input data from the original extract the string, try to return a child from the original string, string, rather than creating a copy. You will create a new string object, but it and your original data shared data space.
  • If you have a return string to method, you should be aware of any case that the result is StringBuffer, change your the function of Definition and enforced so that function directly to return rather than Tongguo create a temporary object.

A more radical approach is to partition a multidimensional array into several parallel one-dimensional array:

  • An array of type Int than an array of Integer type is better, but the same could be summarized in such a principle, two types of arrays Int than a (int, int) the efficiency of an array of objects to be much higher. For other primitive data types, this principle applies.
  •  If you need to create an object that contains a series of Foo and Bar containers (container), remember: two parallel Foo [] and Bar [] than a (Foo, Bar) array of objects much more efficient. (This example also has an exception, when you design the interface API when other code; in this case, the speed of a point on the loss would not have considered. But, in your code inside, you should try to write efficient code. )

In general, as much as possible to avoid creating short-term temporary objects. Less object creation means less garbage collection, which will improve the quality of your program's user experience.

Use their own methods (Use Native Methods)

When dealing with strings, do not hesitate to use as much as possible, such as String.indexOf (), String.lastIndexOf () method with this object itself. Because these methods use C / C + + to achieve, than in a java loop do the same thing 10-100 times faster.

Another point to add clear is that these methods use the cost of Zi Shen Jie Shi Guo's methods than those Gao Henduo, Yin Er, Duiyu minor operations, as Buyongzhelei method.

Better than the use of virtual interfaces

Suppose you have a HashMap object, you can declare it is a HashMap or is just a Map:

Map myMap1 = new HashMap();
HashMap myMap2 = new HashMap();

Which is better?

Generally wise to use the Map, because it can allow you to change the Map interface to implement any of these things, but this "sensible" approach is only applicable to regular programming, not suitable for embedded systems. Reference to the call through the interface will take more than 2 times the time, as opposed to through a specific reference to the virtual function call.

If you choose to use a HashMap, because it is more suited to your program, then use the Map will be worthless. Suppose you have a can restructure your code integrated coding environment, then call the Map of no use, even if you're not sure where at the beginning of your program. (Similarly, public of the API is an exception, the value of a good API is often greater than the efficiency at which point loss)

Better than using a static virtual

If you do not need to access the external object, then make your way to a static method. It will be faster call, because it does not need a virtual function-oriented form. It is also a good practice, because it tells you how to distinguish the nature of the method (signature), calling this method does not change the object state.

As far as possible avoid the use of inherent Get, Set Methods

Like C + + iyangde programming language, often using Get methods (for example i = getCount()) to replace the direct access to the property (i=mCount). This is in C + + programming which is a good habit, because the compiler will access method is set to Inline, and if you want to bind or debug attribute access, you only need to add some code at any time.

In the Android programming, this is not a very good idea. Virtual method call will generate a lot of costs, the cost of queries than the instance of the property even more. We should use the external call functions Get and Set, but internal calls, we should be called directly.

Buffer attribute called Cache Field Lookups

Access object property is much slower than access to local variables. You should not write your code:

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

It should read:

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

(We direct use "this" that these are its member variables)

A similar principle: that no statement in a For the second time in calling a class method. For example, the following code will be implemented again and again getCount () method, which is a great way to waste than you hide it directly to a Int variable.

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

This is a good way, when you call more than once a instances, the direct localization of this example, this example of some of the value assigned to a local variable. 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);

There are four attributes mScrollBar call to mScrollBar buffer to a stack variable among the four members of the property will become four times the call stack access, this will improve efficiency.

Incidentally, the method also can be the same as local variables with the same characteristics.

Final statement of constant

We can look at a class at the top of the following statements:

static int intVal = 42;
static String strVal = "Hello, world!";

When a class of first use, the compiler will call a class initialization method - <clinit>, this method will be 42 deposited into variable intVal, and for strVal string constant in the class file to extract a reference scale, when these values later reference, they will call the property directly.

We can use the keyword "final" to improve the code:

static final int intVal = 42;
static final String strVal = "Hello, world!";

This class will not call es a <clinit> method, because these constants are directly written into the class static attribute initialization file, this initialization directly from the virtual machine to handle. Code will be used to access intVal 42 Integer types, access strVal will use the relative savings in "constant string" to replace a property called.

A class or method declared as "final" and will not bring any benefits of implementation, it can carry out some of the most optimized. For example, if the compiler knows that a quilt class can not be overloaded Get method, it put the function set to Inline.

At the same time, you can also declare local variables final variable. However, this is meaningless. As a local variable, use the final only to make the code more clear (or you have to use inline anonymous access class).

Prudent use of Enhanced For loop

Enhanced For loop (which is often said the "For-each loop") is often used to collect Interface Iterable interface inheritance above. In these objects inside a iterator is assigned to an object to call its hasNext () and next () method. In an array list which you can access the perfunctory own it, in other collector inside, enhanced for loop is equivalent to the use of iterator.

Nevertheless, the following source code shows an acceptable enhanced for loop example:

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 two() {
        int sum = 0;
        for (Foo a: mArray) {
            sum += a.mSplat;

zero () function in each cycle of re-obtain the static properties of the two, get the array length of time.

one () function to everything into local variables, to avoid the class to find attribute called

two () function uses the Java language for the 1.5 version of the loop, the editor generated source code into account the reference copy of the array and the length of the array to a local variable is an array of cases over the better method, which in the main loop does have an additional loading and storage process (apparently saved the "a"), compared to the function one (), it's slowed down a little bit and 4 bytes of growth.

Conclusion, we can get: enhanced for loop in the array which performed well, but when and Iterable object when used with caution, because this creates more of an object.

Avoid Enums to avoid the type listed

Enumerated type is very easy to use, when taking into account the size and speed, they would seem costly, for example:

public class Foo {
   public enum Shrubbery { GROUND, CRAWLING, HANGING }

This will be transformed into a 900 bytes of class file (Foo $ Shrubbery.class). First use, type De initialization Yaozai exclusive method of Qu Miaoshu listed above, call each item returned to load each one has its own Jingtaikongjian, the Pi stored in an array inside (1 Called "$ VALUE "static array). It was a lot of code and data, just to the three integer values.

Shrubbery shrub = Shrubbery.GROUND;

This will cause a static property of the call, if the Final GROUND is a static variable, the compiler will it as a constant in the code nested inside.

Another point to say, through the list, you can get a better API and some compile time checks. Therefore, a more balanced approach is: you should make every method in your public API to use list variables, when dealing with issues on the avoided as much as possible.

In some environments the following by ordinal () method to get a list of integer variables is useful, for example: the following code

for (int n = 0; n < list.size(); n++) {
    if (list.items[n].e == MyEnum.VAL_X)
       // do stuff 1
    else if (list.items[n].e == MyEnum.VAL_Y)
       // do stuff 2

Replace with:

   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 conditions, it will run faster, though not guaranteed.

Package through the use of space within the joint class

We look at the following class declaration

public class Foo {
    private int mValue;

    public void run() {
        Inner in = new Inner();
        mValue = 27;

    private void doStuff(int value) {
        System.out.println("Value is " + value);

    private class Inner {
        void stuff() {

Here we should note that we define an inline type, it calls the external class of private methods and private property. This is a legitimate call, the code should show "Value is 27".

The problem is, in theory Foo $ Inner (background on) should be a completely separate class, it calls irregularities in the private members of the Foo. To compensate for this shortcoming, the compiler produces a synthetic method:

/*package*/ static int Foo.access$100(Foo foo) {
    return foo.mValue;
/*package*/ static void Foo.access$200(Foo foo, int value) {

When the in-class access from the outside "mValue" and called "doStuff" when the inline type will call these static methods, which means you do not directly access the class members, but by way of public access. We talked about the previous indirect access slower than direct access, so this is a language used by the invisible implementation example.

To have a package within the joint space of the direct statement of need to access class properties and methods, we can avoid this problem, philosophical poetry is package space, rather than private space. It runs faster and go in front of things in addition to generating functions. (Unfortunately, it also means that the property also can be the same package the other classes the following direct access to the Wei Fan a standard object-oriented of the principle of private property Shisuo You. Similarly, Ru Guo is a public API you design should carefully consider the use of this optimization)

Avoid the use of floating-point type

Before the release of the Pentium CPU, the game as much as possible the use of type Integer mathematical function is normal. Inside the Pentium processor, floating point processing into it a prominent feature, and the interactive use of floating point and integer integer comparison alone, the former will make your game run faster, the average desktop computer We can use the above free float.

Unfortunately, the embedded processors usually do not support floating-point processing, vaginal teeth all the "float" and "double" is done via software, and some basic floating point operation takes milliseconds to time.

Colleagues, even integer, a number of chips not only multiplication division. In these cases, the integer division and modulus operations are implemented by software. When you create a Hash Table, or a lot of math, this is what you need to consider.

Comparison of some of the standard operation of the time

In order to explain our point of view from, here is a table, including some of the basic operation of the approximate time used. Note that the time is not absolute time, absolute time, taking into account the CPU and clock frequency. Systems, the time will be different in size. Of course, this is a meaningful comparison, we can call different operation than the relative time spent. For example, add a member variable of time is to add a local variable of the four times.

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


Efficient embedded process writing the best way is to figure out what happened to your writing process. If you really want to assign an iterator class, all the way into a List in the use of enhanced for loop, make it a practice of knowingly, rather than an inadvertent omission, but a negative impact.

Prepared and find out what you are doing! You can if you own some of the code of conduct, but must pay attention to what your code is doing, and then start looking for ways to optimize it.
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of [Change] the preparation of efficient Android code

  • Hibernate access picture sample

    General web users to upload picture at treatment would normally uses two types of strategies: First, put directly into the picture in the database Blob field; II database are stored only at the picture on the path of the server information?, Pictures stor

  • How to create a Rails migration mission bigint types of field

    Rails 2.1 will be adopted over the length of INTEGER fields to select the appropriate type of The following code will create a bigint type of field Limit are required attention should be between 5 to 8, but not too much. If you want to bigint, then t ...

  • Hibernate's cache management

    Carried ] [http ://www.cnblogs.com/eflylab/archive/2007/01/11/617276.html Cache is the cache, it is often to improve system performance are the most important means to serve as a reservoir of data and the role of a buffer. Cache for the substantial r ...

  • Hibernate's FetchSize and MaxReslut

    Previously EJB to do paging, EJBQL only provide FirstResult and MaxReslut, recently discovered by Hibernate its HQL also provides FetchSize, checked under the API found almost mean, and then found the next line so someone said: setFetchSize is an opt ...

  • Hundred software developers interview question

    Hundred software developers interview question Think employed to engage in software development of smart people is not easy. The event of accidentally, it will get a pile of low-energy large baboons. I met last year on this matter. You certainly do not wa

  • The company first entered the company I would like to Optimize SQL project

    I was a time not long into the company of people, but also a person to be graduated, but immediately entered the project team, involved in the development. The project is to make a China Telecom Operation System, is a big system. My so-called develop ...

  • EJB

    public transient int counter; / / transient property private String firstname; / / persistent property @ Transient String getLengthInMeter () (...) / / transient property String getName () (...) / / persistent property @ Basic int getLength () (...) / / p

  • Process migration from tomcat to websphere changes

    Process migration from tomcat to websphere changes Because customers use the web application server software used by different what tomcat5, tomcat6, websphere5.1, websphere6.1, weblogic8, and so on, and the software used inconsistent standards, ibm's

  • Collection of articles about hibernate

    Read a few times, or have the need to look at Given the recurring discussion of the applicability of the post hibernate, the wish to have a conclusion Reference Posts: OpenSessionInView will not affect the performance? Choose Hibernate or iBatis? Cho ...

blog comments powered by Disqus
Recent Entries
Tag Cloud
Random Entries