As Android-related devices are embedded devices, we need to pay special attention to efficiency when writing App applications, and they are limited by battery power. This leads to many considerations and limited processing power of embedded devices, so we need to write efficient code as much as possible. This article discusses many ways that developers can make their programs run more efficiently. By following these methods, you can make your programs work best. introduction There are two basic principles for resource-intensive systems: Don't do unnecessary things Don't allocate unnecessary memory All the following content follows these two principles. 1. Avoid creating objects There are no free objects in the world. Although GC creates a temporary object pool for each thread, which can reduce the cost of creating objects, allocating memory is always more expensive than not allocating memory. If you allocate objects in a user interface loop, it will trigger periodic garbage collection, and the user will feel that the interface is intermittent and hiccupy. Therefore, you should try to avoid creating instances of end-of-life objects unless necessary. The following example will help you understand this principle: When you extract a string from user input, try to use the substring function to get a substring of the original data instead of creating another copy of the substring. In this way, 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 for sure that the string will be appended to a StringBuffer, then please change the parameters and implementation of the function to append the result directly to the StringBuffer instead of creating a short-lived temporary object. A more extreme example is to split a multidimensional array into multiple one-dimensional arrays: The fact that int arrays are better than Integer arrays also summarizes a basic fact: two parallel int arrays perform much better than (int, int) object arrays. Similarly, this applies to all combinations of 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 will definitely be more efficient than the (Foo, Bar) array. (There are exceptions, that is, when you build an API and let others call it. At this time, you have to focus on the design of the API interface and sacrifice a little speed. Of course, inside the API, you still have to improve the efficiency of the code as much as possible) In general, it is to avoid creating short-lived temporary objects. Reducing the creation of objects can reduce garbage collection, thereby reducing the impact on user experience. 2. Use local methods When you are working with strings, don't hesitate to use special implementations like String.indexOf(), String.lastIndexOf(), etc. These methods are implemented in C/C++ and are 10 to 100 times faster than Java loops. But it does not mean that we should use native methods completely. The cost of calling native methods is higher than calling interpreted methods. So if it can be avoided, we should not use native methods to do some simple calculations. 3. Choose virtual classes instead of interfaces Suppose you have a HashMap object, you can declare it as HashMap or Map: Map myMap1 = new HashMap(); HashMap myMap2 = new HashMap(); Which one is better? According to 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 reference takes twice as long as calling an entity class reference. If HashMap is completely suitable for your program, then there is no value in using Map. If there are some places you are not sure about, avoid using Map first, and leave the rest to the refactoring function provided by the IDE. (Of course, the public API is an exception: a good API often sacrifices some performance) 4. Using static methods is better than virtual methods If you don't need to access an object's member variables, declare the method as static. Virtual methods execute faster because they can be called directly without the need for a virtual function table. In addition, you can also use the declaration to show that calling this function will not change the state of the object. 5. No getters and setters In many native languages like C++, getters (e.g., i = getCount()) are used to avoid direct access to member variables (i = mCount). This is a very good habit in C++ because the compiler can inline the access, and you can add code at any time if you need to constrain or debug variables. On Android, this is not a good idea. Virtual methods have a much higher overhead than direct access to member variables. In general interface definitions, getters and setters can be defined in an OO way, but in general classes, you should access variables directly. 6. Cache member variables locally Accessing member variables is much slower than accessing local variables. The following code:
Another similar principle is: never call any method in the second condition of for. As shown in the following method, the getCount() method is called in each loop, which is much more expensive than saving the result in an int first. for (int i = 0; i < this.getCount();i++) dumpItems(this.getItem(i)); Similarly, if you want to access a variable multiple times, create a local variable for it first, for example:
There are 4 accesses to the member variable mScrollBar here. If it is cached locally, the 4 member variable accesses will become 4 more efficient stack variable accesses. By the way, method parameters have the same performance as local variables. 7. Use constants Let's look at these two declarations at the beginning of the class: static int intVal = 42; static String strVal = "Hello, world!"; The compiler will generate a method called <clinit> to initialize the class. This method will be executed when the class is used for the first time. The method will assign 42 to intVal and a reference to the constant table in the class to strVal. When these values are needed later, 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!”; Now, the class no longer needs the <clinit> method, because when the member variables are initialized, the constants are saved directly to the class file. The code using intVal is directly replaced with 42, and the code using strVal will point to a string constant instead of using the member variable. Declaring a method or class as "final" will not bring performance improvements, but it will help the compiler optimize the code. For example, if the compiler knows that a "getter" method will not be overloaded, the compiler will inline the call to it. You can also declare local variables as "final", but again, this will not improve performance. Using "final" only makes local variables look clearer (but sometimes this is necessary, such as when using anonymous inner classes). 8. Use foreach with caution 9. Avoid using enumerations Conclusion: The best way to write correct and efficient code for embedded systems is to understand what your code is doing. If you do want to allocate an iterator or use enhanced loop syntax on Lists anyway, then it must be a deliberate choice and not an inadvertent side effect. Forewarned is forearmed. Know what you are doing. Write code in your own style, but think carefully about what it is doing and find ways to speed it up. |
<<: Android learns to visualize database operations in one minute (no ROOT required)
>>: China Unicom WO+ Dream Factory will come to Xiamen on January 30, so stay tuned!
[[428179]] Many people may not know that in iOS15...
As everyone knows, ASO refers to the search optim...
Finally, students who hold Android devices no lon...
Qoros, a little-known brand, fully illustrates wh...
The ordinary creative style of Baidu bidding prom...
Shark watching in the lake? It's not a fantas...
1. The "U" of a server is a unit that r...
This article analyzes and discusses how to design...
Some time ago, a topic on the Internet caused a h...
The course "Zuo Zhijian - 15 Practical Finan...
◎ Science and Technology Daily reporter Xue Yan S...
Short video marketing is very popular, first ther...
On the evening of April 11, Tianhai Investment, a...
Let’s take a look back at the last month of 2014....
Author: Jiang Wei Xi'an Medical College Zhou ...