How to write efficient Android code

Source: Internet
Author: User

Android-based devices are an embedded device category that focuses on efficiency and is limited by battery power when writing apps. This leads to embedded devices with a lot of consideration and limited processing power, so we need to write efficient code as much as possible. This article discusses a lot of ways that developers can make their programs run more efficiently, and by following these methods you can make your program work best.


Introduction
For resource-intensive systems, there are two basic principles:

Don't do unnecessary things.

Do not allocate unnecessary memory


All of the following are in accordance with these two principles.

1. Avoid building objects

There are no free objects in the world. Although the GC creates a temporary object pool for each thread, it can make it less expensive to create objects, but allocating memory is always more expensive than allocating memory.
If you allocate object memory in the user interface loop, it will cause periodic garbage collection, and the user will feel like a hiccup in the interface.
Therefore, unless necessary, try to avoid instances of the object. The following example will help you understand this rule:


When you intercept a string of data from user input, try to use the SUBSTRING function to get a substring of the original data instead of creating a separate copy for the substring. So you have a new string object that shares a char array with the original data.
If you have a function that returns a String object, and you know exactly if the string will be appended to a stringbuffer, change the parameter and implementation of the function, and attach the result directly to the stringbuffer instead of creating a short-lived temporary object.
A more extreme example is the partitioning of multidimensional arrays into multiple one-dimensional arrays:

An int array is better than an integer array, which also summarizes the basic fact that two parallel int arrays perform much better than (Int,int) object arrays. In the same vein, this test is used for all basic types of combinations.
If you want to use a container storage (foo,bar) tuple, try using two separate foo[] arrays and bar[] arrays, which is certainly more efficient than (foo,bar) arrays. (The exception is when you build an API to let others call it.) At this point you should pay attention to the design of API excuses to sacrifice a bit of speed. Of course, within the API, you still need to improve the efficiency of the code as much as possible.
Overall, it is to avoid creating short-lived temporary objects. Reducing the creation of objects reduces garbage collection, which in turn reduces the impact on the user experience.


2. Using local methods

When you are dealing with strings, do not hesitate to use String.IndexOf (), String.LastIndexOf () and other special implementation methods. All of these methods are implemented in C + + and are 10 to 100 times times faster than Java loops.
But it is not intended to fully use local methods, and the cost of calling local methods is higher than the invocation interpretation method. So if you can avoid it, you should not use local methods to do some operations that are not complex.


3. Choose a virtual class instead of an interface

Suppose you have a HashMap object that you can declare as a hashmap or a map:


Map myMap1 = new HashMap ();

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


It's better to follow the traditional view map, 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. Invoking a reference to an interface can take more than one time to invoke a reference to an entity class. If HashMap is perfectly suited to your program, then using map is of little value. If there are areas where you are unsure, avoid using map, and the rest of the refactoring functionality provided by the IDE is good. (Of course, the public API is an exception: a good API often sacrifices some performance)





4, using static method than virtual method good


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



5. No getter and setter


In many native languages, such as C + +, getter (for example: i = GetCount ()) is used to avoid direct access to member variables (i = mCount). This is a good habit in C + + because the compiler is able to access inline, and 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 a virtual method is much larger than the direct access member variable. In a common interface definition, getters and setters can be defined in oo ways, but in a generic class you should directly access the variables.




6. Cache member variables locally


Accessing member variables is much slower than accessing local variables, the following snippet:

for (int i = 0; i < This.mcount; i++)


Dumpitem (This.mitems[i]); You should write:

int count = This.mcount;


item[] items = this.mitems;


for (int i = 0; i < count; i++)


Dumpitems (Items[i]); (The display uses "This" to indicate that these are member variables)



Another similar principle is that you should never call any method in the second condition of a for. As shown in the following method, the GetCount () method is called at each loop, so it is much more expensive to save the results first than you would in an int.

for (int i = 0; i < This.getcount (); i++)

Dumpitems (This.getitem (i)); also if you want to access a variable multiple times, it is also a good idea to create a local variable for it, 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 accesses to the member variable Mscrollbar, and if it is cached locally, 4 access to the member variable becomes 4 more efficient access to the stack variable.

By the way, the parameter of the method is the same as the performance of the local variable.





7. Using Constants


Let's take a look at these two paragraphs in front of the class declaration:

static int intval = 42;

static String Strval = "Hello, world!";


The compiler generates a method called the initialization class for <clinit>, which is executed when the class is used for the first time. The method assigns 42 to Intval, and then assigns a reference to the constant table in the class to Strval. When these values are to be used later, they are 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!";

Now, the class no longer needs the <clinit> method, because when the member variable is initialized, the constants are saved directly to the class file. The code used for Intval is replaced directly with 42, whereas using Strval points to a string constant instead of using a member variable.


Declaring a method or class as "final" will not result in a performance boost, but it will help the compiler optimize the code. For example, if the compiler knew that a "getter" method would not be overloaded, the compiler would take an inline call to it.

You can also declare local variables as "final", which also does not result in performance gains. Using "final" can only make the local variable look clearer (but there are times when it is necessary, such as when using an anonymous inner class).


8. Use foreach with caution

9. Avoid using enumerations

Conclusion:

The best way to write the right and efficient code for an embedded system is to understand what your code is doing. If you do want to assign an iterator or, anyway, use the enhanced loop syntax on the lists, then it must be a deliberate choice, not a side effect of careless heart. Everything is pre-set, not pre-waste. Be sure to know what you are doing. Write the code in your own style, but be sure to think carefully about what the code does and find a way to speed it up

How to write efficient Android code

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.