[Change] how to write efficient code for Android

http://mobile.csdn.net/n/20090803/265358.html

Modern handheld devices, so much the phone, more like a computer in your hand. However, even the "fastest" of the handheld device, its performance is also not keep up with an ordinary desktop computers.

That is why we write Android application in time to pay special attention to efficiency. These devices are not so fast, and constrained by battery power. This means that the device does not have more capacity, we must try to write effective procedures.

This article discusses a number of developers to allow them to run a more effective way, in accordance with these methods, you can make your program to maximize effectiveness.

Introduction

For resource-system, there are two basic principles:
1. Do not do unnecessary things
2. Do not allocate unnecessary memory

All content is in accordance with the following two principles.

Some people may soon pop up, most of the attribution of this section, "reckless optimization" (xing: see [The Root of All Evil]), denied micro-optimization (micro-optimization. Xing: code optimization, compared to structural optimization) will bring many problems, such as not using more efficient data structures and algorithms. But in the handheld device, you have no choice. If you think that Android virtual machine performance and desktop rather, your application is likely to start taking up all system memory (xing: memory is small), this will make your application as slow as a snail, more let alone to do the other to operate.

Android's success depends on your program to provide the user experience. This kind of user experience, partly dependent on your program is fast and flexible response, or response to slow and rigid. Because all of the programs are run on the same equipment, all together, which if in the same cars on the road. And this document is equivalent to obtain driver's license before you have to learn the rules of the road. If we all do it in accordance with these rules, drivers will be very smooth, but if you do not, you may car crash. This is why the importance of these principles.

When we get right before the theme Watch, also have to remind you: No matter whether the VM to support real-time (JIT) compiler (xing: it allows real-time will automatically compile Java to explain the cost of machine type machine language, so that program execution faster. some JVM JIT compiler included.), mentioned below, these principles are established. If the target we have exactly the same two methods, when in the interpretation of the implementation of foo () than the bar () fast, then after compilation, foo () is still better than bar () faster. Therefore, the compiler can not look to save your program.

Avoid the creation of objects

The world is no free object. Although GC have been established for each thread pool of temporary objects can make the cost of creating objects become smaller, but the allocation of memory is always better than not allocate memory for the price great.

If you are in the user interface object memory allocation cycle, it will lead to periodic garbage collection, the user interface will feel the same meal as the meal of hiccup.

Therefore, unless absolutely necessary, try to avoid the object instance. The following examples will help you understand this principle:

When you enter the data from the user's interception of a string, try to use the substring function to obtain the raw data of a sub-string, rather than the establishment of a copy of another substring. So you have a new String object with the original data share a char array.
If you have a function that returns a String object, and you know exactly the string will be appended Dao a StringBuffer, Name, please change the function arguments and implementations, directly attached to the StringBuffer the results, the Er Bu again a short-lived temporary objects.
A more extreme example is the multi-dimensional array into multiple one-dimensional array.

better than the Integer array of int arrays, which summarizes a basic fact, more than two parallel int array (int, int) array of objects much better performance. Similarly, this trial was a combination of all basic types.
If you want to use a container storage (Foo, Bar) per group, try to use two separate Foo [] array and the Bar [] array, must be better than (Foo, Bar) an array more efficient. (There are exceptions, when you create a API, so that when people call it. This time you should pay attention to the design of the API excuse to sacrifice a little speed. Of course, the internal API, you have to raise as much as possible code efficiency)

On the whole, is to avoid creating short-lived temporary objects. Create an object can be reduced to reduce garbage collection, thereby reducing the impact on user experience.

Use the local method

When you are dealing with strings, do not begrudge the use String.indexOf (), String.lastIndexOf () and other special methods to achieve (specialty methods). These methods are using C / C + + implementation, compared to Java loop 10 to 100 times faster.

Real analog interface to good use

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

Map myMap1 = new HashMap ();
HashMap myMap2 = new HashMap ();
Which is better?

Map according to the traditional view would be better, because you can change his specific implementation class, as long as the class inherits from the Map Interface. The traditional view is correct for the traditional procedure, but it is not suitable for embedded systems. Called an interface reference to an entity class than calling a reference to more than double the time spent.

If HashMap perfectly suited for your program, then use the Map of little value. If you are not sure in some places, first to avoid the use Map, the rest to the IDE provides refactoring features better. (Of course the public API is an exception: a good API is often at the expense of some performance)

Method with static method better than the virtual

If you do not need to access an object member variable, then the method declared as static. Faster implementation of virtual methods, because it can be called directly without the need for a virtual function table. Also you can demonstrate this by declaring the function call does not change the state of the object.

Do not have getter and setter

In many local languages such as C + +, will use the getter (for example: i = getCount ()) to avoid direct access to the member variable (i = mCount). In C + +, this is a very good habit, because the compiler can inline access restrictions or if you need to debug variables, you can add the code at any time.

In Android on, it is not a good idea. Overhead of virtual method is much greater than the direct access to the member variable. In the generic interface definitions, can follow the OO approach and the definition of getters setters, but in general the class, you should have direct access to variables.

The member variable to the local cache

Access member variables is much slower than access to local variables, the following piece of code:

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

Best to change this:

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

(Using "this" is to show that these are the member variable)

Another similar principle is: Never in the second condition for any method call. Method as shown below, in each cycle will be called when the getCount () method to do so than you int first results in a large number of saved expenses.

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

Similarly, if you want to visit several times a variable, it is also a good idea to create 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);
                mScrollBar.setParams(computeHorizontalScrollRange(),computeHorizontalScrollOffset(),computeHorizontalScrollExtent(), false);
                mScrollBar.draw(canvas);
        }
}

There are 4 access member variables mScrollBar, if it is cached to the local, 4 members of the variable access will become four times more efficient access to stack variables.

The other is the method parameters and local variables the same efficiency.

Use constant

Let us look at these two in front of the class declaration:

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

Will its generates a class called <clinit> initialization method is used when the class first time this method will be executed. Method 42 will be assigned to intVal, then a reference point scale class often assigned strVal. When later use these values when the member variables in the table to find them.

Now we do to improve the use of "final" Keyword:

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

Now, the class is no longer needed <clinit> way, because when the member variable initialization, will be kept constant to the class file directly. The code used intVal be directly replaced with 42, while the use of strVal's will point to a string constant, rather than using the member variable.

A method or class declaration for the "final" will not bring performance improvements, but will help the compiler optimize the code. For example, if the compiler knows that a "getter" methods will not be overloaded, the compiler will inline calls for its use.

You can also declare local variables for the "final", as it will not bring about performance improvements. Use the "final" can only appear more clearly some of the local variables (but also sometimes it is necessary, such as when using anonymous inner classes) (xing: the original is or you have to, eg for use in an anonymous inner class)

Prudent use foreach

foreach can be used to achieve the Iterable interface, a collection of types. These objects will be assigned a foreach iterator, then calls the hasNext () and next () method. You'd better deal with ArrayList object using foreach, but a collection of objects on the other, foreach is equivalent to using the iterator.

The following shows an acceptable use foreach:

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;
                }
        }
}

At zero () in each loop will visit the two static variables, to obtain a length of the array.
retrieves the static field twice and gets the array length once for every iteration through the loop.

In one () in all the member variables to store local variables.
pulls everything out into local variables, avoiding the lookups.

two () uses introduced in java1.5 foreach syntax. Compiler will be a reference to the array and the array length save to a local variable, which is very good access to the array elements. But each time the compiler will generate an extra loop on the local variables store operation (on a variable access) that would more than one () a 4 bytes, the speed is slightly slower.

In summary: foreach syntax array performance when used well, but when applied to other collection object to be careful because it will generate additional objects.

Avoid the use of enumeration

Enum is very convenient, but unfortunately it at the expense of implementation and substantial increase in the speed and file size. For example:

public class Foo (public enum Shrubbery (GROUND, CRAWLING, HANGING))

Will produce a 900-byte. Class files (Foo $ Shubbery.class). It was first called, this class will call the initialization method to prepare for each enum. Each enumeration item will be declared as a static variable, was assigned. Then these static variables in a named "$ VALUES" static array variable. And so lots of code, just to use three integers.

Like this:

Shrubbery shrub = Shrubbery.GROUND; will cause a reference to the static variable, if the static variable is final int, the compiler will inline the constant directly.

On the one hand that the use of enumeration variables can make your API better, and provide compile-time checks. So often when there is no doubt you should select the enum public API. But when the performance is restricted, you should avoid such actions.

In some cases, use of ordinal () method for enumeration of integer variables would be better, for example, will:

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
}

Make some improvements in performance, but this is not the ultimate solution.

Will be used in conjunction with the internal class variable declarations within the package

Consider the following class definition:

public class Foo (private int mValue; public void run () (Inner in = new Inner (); mValue = 27; in.stuff ();) private void doStuff (int value) (System.out.println ("Value is "+ value);) private class Inner (void stuff () (Foo.this.doStuff (Foo.this.mValue );}}}

This key is, we define an internal class (Foo $ Inner), it needs to access a private field outside class variables and functions. This is legitimate, and will print out the results we had hoped "Value is 27".

The problem is that technically speaking (in the background) Foo $ Inner is a completely separate category, it should be direct access to the private members of Foo is illegal. To cross this gap, the compiler needs to generate a set of methods:

static int Foo.access $ 100 (Foo foo) (return foo.mValue;) static void Foo.access $ 200 (Foo foo, int value) (foo.doStuff (value);)

Internal class in each visit "mValue" and "doStuff" method will call these static methods. That is, the above code shows a problem, you are through the interface method to access these member variables and functions not directly call them. We have said earlier, use the interface method (getter, setter) is slower than direct access. Therefore, this example is produced in a specific syntax following a "hidden" performance barriers.

Accessed by the internal class variable and function declarations to package range from the private range, we can avoid this problem. This allows code to run faster, and avoid additional static methods. (Unfortunately, these fields and methods can be a package with other classes within the direct access, which is the classic OO principles. So when you design the public API should be cautious when using this optimization principle)

Avoid the use of floating point

Before the advent of the Pentium CPU, game designers have done is up to integers. With the arrival of the Pentium, floating-point processor into the CPU built-in features, with the use of floating point and integer can make your game run more smoothly. Usually on the desktop computer, you are free to use floating-point operations.

But sorry, embedded processors usually do not support floating-point hardware, all of the "float" and "double" of the operation are achieved through software. Some of the basic floating-point operations, or even need to milliseconds to complete.

Even integer, some chips have hardware support on the multiplication of the lack of division support. This case, the integer division and modulo operation is accomplished with software. So when you're using a hash table or do a lot of math must be careful when.

分类:Mobile 时间:2010-05-31 人气:1107
分享到:
blog comments powered by Disqus

相关文章

  • Data structures and algorithms book recommendations 2010-09-23

    If the computer system open only three courses, then this will definitely be three courses: discrete mathematics, data structures and algorithms, compiler theory. If only one course open, then surely the rest are: data structures and algorithms. Nikl

  • Data Structures and Algorithms Book Recommendation 2010-09-23

    If the computer system is only open three courses, this course will definitely be three: discrete mathematics, data structures and algorithms, compiler theory. If only one course open, then the rest will surely be: data structures and algorithms. Nik

  • Is the nature of language and software data structures and algorithms 2010-02-25

    1. Language is a data structure and algorithm is composed of software, too. 2. The language of data structures and algorithms are those defined by the language definition (coded), and software, in addition to the language's own data structures and al

  • java study notes data structures and algorithms (zero) 2011-04-28

    The importance of data structures and algorithms well known, but sometimes we will find a lot of typical data structures in java already been achieved, such as linked lists, stacks, etc., it is precisely because, unlike C, C + + programmers as needed

  • Computational Geometry in GIS and related data structures and algorithms 2011-07-28

    Two of GIS and computational geometry-related data structures and algorithms Delaunay triangulation algorithm Delaunay triangulation and Veronoi map each dual graph. Commonly known as triangulation maximizes the smallest angle. 2d only concerned with

  • Data structures and algorithms 2010-03-22

    Data structures and algorithms found in more and more important, in order to better communication with you data structure and algorithm of knowledge, data structures and algorithms group 65,145,281

  • Data Structures and Algorithms (Java Edition) [2010/7/3] [0] 2010-07-03

    I have a small master, and now companies are tmd too utilitarian, and to want to work on really tmd myopia! Today, then get the data structure Java version again, after a whole have to get down those grandchildren! DATA STRUCTURES AND ALGORITHMS IN J

  • Visualization of data structures and algorithms 2011-05-07

    Visualization of data structures and algorithms Reference learning is very good. http://sd.csdn.net/a/20110506/297285.html

  • Java data structures and algorithms, the first chapter, study notes 2010-05-06

    1. Data structure is the data in computer memory or disk structure 2. Examples of array data structures, stacks, linked lists, etc. 3. Algorithm is a specific task to complete the process 4.java, usually achieved through the class method. 5. Data str

  • Large amounts of data processing and storage code optimization process 2010-12-31

    1. Reproduce the original scene: The module is mainly responsible for uploading the client contains the phone number of a txt, one line of a phone number. Server to read and parse the file, parsing validation process needs to be done. For example: th

iOS 开发

Android 开发

Python 开发

JAVA 开发

开发语言

PHP 开发

Ruby 开发

搜索

前端开发

数据库

开发工具

开放平台

Javascript 开发

.NET 开发

云计算

服务器

Copyright (C) codeweblog.com, All Rights Reserved.

CodeWeblog.com 版权所有 闽ICP备15018612号

processed in 0.033 (s). 13 q(s)