How to Write efficient android code and android code

Source: Internet
Author: User

How to Write efficient android code and android code

Android-related devices are embedded devices. When writing apps, you must pay special attention to efficiency and be limited by battery power. As a result, embedded devices have many considerations and limited processing capabilities. Therefore, we need to write efficient code as much as possible. This article discusses a lot of ways for developers to make their program run more effective. Following these methods, you can make your program play the most effective.


Introduction
There are two basic principles for a resource-consuming system:

Do not do unnecessary things

Do not allocate unnecessary memory


All the following content follows these two principles.

1. Avoid object Creation

There are no free objects in the world. Although GC creates a temporary object pool for each thread, it can reduce the cost of object creation, but the cost of memory allocation is always higher than that of memory allocation.
If you allocate the object memory in the user interface loop, it will lead to periodic garbage collection, and the user will feel that the interface is as choppy.
Therefore, unless necessary, try to avoid the instance of the object as much as possible. The following example will help you understand this principle:


When you extract a string from user input data, try to use the substring function to obtain a substring of the original data, instead of creating a copy for the substring. In this way, you have a new String object, which shares a char array with the original data.
If you have a function that returns a String object, and you know exactly that the String will be appended to a StringBuffer, change the parameter and implementation method of this function, directly append the result to StringBuffer, instead of creating a short-lived temporary object.
A more extreme example is to divide a multi-dimensional array into multiple one-dimensional arrays:

The int array is better than the Integer array, which also summarizes the basic fact that two parallel int arrays provide much better performance than the array of (int, int) objects. Similarly, this is intended for a combination of all basic types.
If you want to use a container to store (Foo, Bar) tuples, try to use two separate Foo [] arrays and Bar [] arrays, which must be equal to (Foo, Bar) array efficiency is higher. (There is also an exception, that is, when you create an API to allow others to call it. At this time, you should pay attention to the design of API excuses and sacrifice a little speed. Of course, you still need to improve the code efficiency as much as possible within the API)
In general, it is to avoid creating short-lived temporary objects. Reduce the creation of objects to reduce the garbage collection, and thus reduce the impact on user experience.


2. Use local methods

When processing strings, do not use special implementation methods such as String. indexOf () and String. lastIndexOf. These methods are implemented using C/C ++, which is 10 to 100 times faster than Java loops.
However, it is not necessary to use the local method completely. The cost of calling the local method is higher than that of calling the interpretation method. So if you can avoid this, you should not use local methods to perform some non-complex operations.


3. Select virtual classes instead of interfaces.

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


Map myMap1 = new HashMap ();

HashMap myMap2 = new HashMap (); which one is better?


In the traditional view, Map is better, because you can change its specific implementation class as long as the class inherits from the Map interface. The traditional view is correct for traditional programs, but it is not suitable for embedded systems. Calling an interface takes twice as long as calling an object class. If HashMap is perfect for your program, using Map has no value. If you are not sure about some items, avoid using Map first, and leave the rest to the refactoring function provided by IDE. (Of course, a public API is an exception: A good API often sacrifices some performance)


 


4. Better static method than virtual Method


If you do not need to access the member variables of an object, declare the method as static. The virtual method runs faster because it can be called directly without a virtual function table. In addition, you can declare that the function call does not change the object state.


 
5. getter and setter are not required.


In many local languages such as C ++, getter (for example, I = getCount () is used to avoid direct access to the member variable (I = mCount ). This is a good habit in C ++, because the compiler can be accessed inline. If you need to constrain or debug variables, you can add code at any time. On Android, this is not a good idea. The overhead of the virtual method is much greater than that of directly accessing the member variable. In the general interface definition, getters and setters can be defined according to the OO method, but in the general class, you should directly access the variable.


 

6. cache member variables locally


Accessing member variables is much slower than accessing local variables. The following code:

For (int I = 0; I <this. mCount; I ++)


DumpItem (this. mItems [I]); you should write it:

Int count = this. mCount;


Item [] items = this. mItems;


For (int I = 0; I <count; I ++)


DumpItems (items [I]); (this is used to indicate that these are member variables)


 
Another similar principle is: Never call any method in the second condition of. As shown in the following method, the getCount () method is called every time a loop is executed, which is much more overhead than saving the result in an int.

For (int I = 0; I <this. getCount (); I ++)

DumpItems (this. getItem (I); similarly, if you want to access a variable multiple times, you 'd better create a local variable for it first, 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 (),

Computehorizontalscroloffset (),

ComputeHorizontalScrollExtent (), false );

MScrollBar. draw (canvas );
}
}


Here, the member variable mScrollBar is accessed four times. If it is cached locally, the four member variable accesses will become four more efficient stack variable accesses.

By the way, the performance of method parameters is the same as that of local variables.


 


7. Use Constants


Let's take a look at the Declaration of the two paragraphs before the class:

Static int intVal = 42;

Static String strVal = "Hello, world !";


The compiler generates an initialization class method called <clinit>, which is executed when the class is used for the first time. The method will assign 42 to intVal, and then assign a reference pointing to a common table in the class to strVal. When these values are used in the future, they will be found in the member variable table.


We can make some improvements by using the "final" Keyword:

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

Currently, the <clinit> method is no longer required for classes, because constants are directly saved to class files during member variable initialization. The code that uses intVal is directly replaced with 42, and strVal points to a String constant instead of a member variable.


Declaring a method or class as "final" will not improve the performance, but will help the compiler optimize the code. For example, if the compiler knows that a "getter" method will not be overloaded, the compiler will call it inline.

You can also declare the local variable as "final" without performance improvement. Using "final" can only make the local variables look clearer (but sometimes this is required, for example, when using anonymous internal classes ).


8. Use foreach with caution

9. Avoid Enumeration

Conclusion:

The best way to write correct and efficient code for embedded systems is to understand what your code is to do. If you really want to allocate an iterator or use the enhanced loop syntax on Lists anyway, it must be a well-thought-out option, rather than a side effect. Everything should be done before it is done. Be sure to know what you are doing. Write code in your own style, but you must carefully consider what the code is doing and find a way to speed up

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.