[Android Advanced]android performance optimization

Source: Internet
Author: User

Android performance optimized for proper management of memory moderation using service

If the application needs to use a service to perform background tasks, the service should be run only when the task is executing. When a service is started, the system tends to keep the process on which the service depends, and the number of processes that the system can cache in LRUCache is reduced, resulting in more performance when switching programs. We can use Intentservice, which stops automatically when the background task executes and avoids the service's memory leak.

Free memory when the interface is not visible

When the user opens another program and our program interface is not visible, we should release all resources that are related to the interface. Rewrite the activity of the Ontrimmemory () method, and then in this method to listen to the level of Trim_memory_ui_hidden, once the trigger indicates that the user left the program, the resource release operation can be done at this time.

Freeing memory when memory is tight

The Ontrimmemory () method also has a number of other types of callbacks that can notify us when the phone memory is down, and we should decide how to release the resources of the application based on the level passed in the callback.

Avoid wasting memory on bitmap

When reading a bitmap picture, never load the desired resolution. You can compress operations such as pictures.

is a collection of data that has been optimized

Android provides a series of optimized data collection tools such as Sparsearray, Sparsebooleanarray, Longsparsearray, which can make our programs more efficient. The HashMap tool class is relatively inefficient because it needs to provide an object entry for each key-value pair, and Sparsearray avoids the time when the base data type is converted to the object data type.

Know the cost of memory
    • Using enumerations typically consumes more than twice times more memory than using static constants, as far as possible without using enumerations
    • Any Java class, including anonymous classes and internal classes, takes up about 500 bytes of memory space
    • An instance of any class consumes 12-16 bytes of memory, so creating instances frequently can also affect memory on certain programs.
    • When using HashMap, even if you only set a key for a basic data type, such as int, but also allocate memory according to the size of the object, about 32 bytes instead of 4 bytes, it is best to use the optimized data collection
Use abstract programming with caution

Using abstract programming on Android brings additional memory overhead, because abstract programming methods require additional code that is not executed at all, but also mapped into memory, which not only consumes more memory, but also decreases execution efficiency. Therefore, it is necessary to use abstract programming rationally.

Try to avoid using the dependency injection framework

Using the dependency injection framework seems to remove the tedious operations of the Findviewbyid (), but these frameworks often need to go through a long initialization process in order to search for annotations in the code, and load some objects that you can't use into memory. These objects will always be used in memory space, it may be a long time to be released, so it may be more than a few lines of code is better choice.

Using multiple processes

With caution, most applications should not run in more than one process, and if used improperly, it will even add extra memory instead of saving memory for us. This technique is better suited to what needs to be done in the background to complete a separate task, and the foreground is completely separate from the scene. For example, music playback, shutdown software, has been completely controlled by the service music playback, the system will still be a lot of UI memory to retain. This scenario is ideal for use with two processes, one for UI presentation and the other for continuous music playback in the background. For implementing multiple processes, simply declare an android:process property on the application component of the Manifast file. The process name can be customized, but preceded by a colon, indicating that the process is a private process for the current application.

Analyze Memory usage

It is not possible for the system to allocate all of the memory to our application, and each program will have a memory limit that can be used, known as the heap size. Different cell phone heap size is different, the following code can get the heap size:

ActivityManager manager = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);int heapSize = manager.getMemoryClass();

The results are returned in megabytes, where the memory of the application cannot exceed this limit, or oom will occur.

The GC operation of Android

The Android system triggers GC operations at the right time, and once the GC is in place, some objects that are no longer used are recycled. The GC operation starts with an object called roots, and all the objects it can access indicate that it is still in use and should be preserved, while the rest of the pair means that it is no longer in use.

Memory leaks in Android

The garbage collection mechanism in Android does not prevent memory leaks from causing memory leaks The main reason is that some live objects hold references to other objects that should be recycled, causing the garbage collector to fail to reclaim those objects, which is a memory leak. For example, a system component like activity, which contains many controls and even pictures, is a serious memory leak if it cannot be reclaimed by the garbage collector.
For example, defining an inner class in mainactivity, instantiating an inner class object, creating a new thread in an inner class that executes a dead loop, causes the internal class resource to be unable to be freed, mainactivity controls and resources cannot be freed, and oom can be used with a series of tools Like Leakcanary.

High-performance coding optimization

are some micro-optimization, in terms of performance can not see any significant improvement. The use of appropriate algorithms and data structures is the most important means of optimizing program performance.

Avoid creating unnecessary objects

Unnecessary objects We should avoid creating:

    • If you have a string that needs to be stitched together, you might prefer to use stringbuffer or StringBuilder for stitching instead of the plus connector, because you use the plus sign to connect inode to create extra objects, the longer the concatenated string, the lower the performance of the plus connector.
    • In cases where there is no special reason to use the base data type instead of the encapsulated data type, int is more efficient than integer and the other data types are the same.
    • When the return value of a method is a string, it is often necessary to determine what the string does, and if it is clear that the caller will re-stitch the returned string, consider returning a StringBuffer object instead, Because it is possible to return a reference to an object, the return string is a temporary object that creates a short life cycle.
    • An array of basic data types is also preferable to an array of object data types. Another two parallel arrays are more efficient than an encapsulated array of objects, for example, foo[] and bar[], which are much more efficient to use than a custom (Foo,bar) [] array.

As little as possible to create temporary objects, fewer objects mean fewer GC operations.

Static better than abstract

If you do not need to access some of the fields in the system, just want to invoke some of its methods to complete a common function, then you can set this method to a static method, the call speed of 15%-20%, and do not need to call this method to specifically create objects, There is no need to worry about whether the method will change the state of the object after it is called (static methods cannot access non-static fields).

Use the static final modifier for constants
staticint42;  static"Hello, world!";  

The compiler generates an initial method for the above code, called a method, which is called when the class is first used. This method assigns a value of 42 to intval and extracts a reference assignment from the string constant table to Strval. When the assignment is complete, we can access the specific value by the way the field is searched.

Final to optimize:

staticfinalint42;  staticfinal"Hello, world!";  

This way, defining a class does not require a method, because all constants are initialized in the initializer of the Dex file. When we call Intval, we can point directly to the value of 42, while calling Strval uses a relatively lightweight string constant instead of the way the field is searched.

This optimization is valid only for basic data types and constants of type string, and is not valid for constants of other data types.

Using enhanced for-loop syntax
Static  class Counter {      intMCount; } counter[] Marray = ... Public voidZero () {int sum=0; for(inti =0; i < marray.length; ++i) {sum+ = Marray[i].mcount; }  } Public voidOne () {int sum=0; counter[] LocalArray = Marray;intlen = localarray.length; for(inti =0; i < Len; ++i) {sum+ = Localarray[i].mcount; }  } Public voidBoth () {int sum=0; for(Counter A:marray) {sum+ = A.mcount; }  }

Zero () is the slowest, each time to calculate the length of the Marray, one () is much faster, and the other () FANGFA is the fastest on a device without JIT (Just in time Compiler) and runs on a JIT-based device with the same efficiency as one () , it is important to note that this writing needs to be JDK1.5 before it is supported.

Tips:arraylist handwriting loops are faster than the enhanced for loop, which is not the case with other collections. As a result, the enhanced for loop is used by default, and the traversal ArrayList uses the traditional looping method.

Use a system-encapsulated API

The system does not provide the API to complete the functions we need to write their own, because the use of the system's API is much faster than the code we write ourselves, many of their functions are carried out through the bottom of the assembly mode.
For example, the ability to implement array copies, using loops to assign values to each of the elements in a set, is certainly possible, but using the System.arraycopy () method provided directly in the system will make the execution more efficient 9 times times faster.

Avoid calling the Getters/setters method internally

The idea of object-oriented encapsulation is not to expose fields inside the class to the outside, but rather to provide specific methods to allow external manipulation of the inner fields of the corresponding class. However, in Android, field search is much more efficient than method calls, and we may be able to access a field 3 to 7 times times faster than accessing the field through the Getters method. But to write code or to follow the object-oriented thinking, we should be able to optimize the place to optimize, such as to avoid the internal call getters/setters method.

Layout optimization Tips reusing layout files

Tags can allow the introduction of another layout in one layout, so for example, all the interfaces of our program have a common part, this is the best way to do this is to extract the public part of a separate layout, and then each interface layout file to reference the public layout.

Tips: If we are going to overwrite the layout property in the label, we have to overwrite both the Layout_width and Layout_height properties, otherwise the overwrite Xiaoguo will not take effect.

tags are used as a secondary extension of the label, and its primary purpose is to prevent redundant layout nesting when referencing a file when referencing a layout file. The more nested the layout, the more time it takes to parse and the worse the performance. Therefore, you should write a layout file so that the number of nested layers is as low as possible.

For example, use a layout in LinearLayout. There is another linearlayout, then there is a redundant layout nesting, using the merge can solve the problem.

Load layout only when needed

Elements in a layout are not displayed together, and in ordinary cases only some of the commonly used elements are displayed, while those that are not commonly used are displayed only when the user makes certain actions.

Example: Fill in the information is not required to fill in, there is an option to add more fields, when the user needs to add additional information, the other elements are displayed on the interface. With visible performance generally, you can use Viewstub. Viewstub is also a view, but no size, no drawing function, no participation in the layout, resource consumption is very low, can be considered completely without impacting performance.

<ViewStub           android:id="@+id/view_stub"          android:layout="@layout/profile_extra"          android:layout_width="match_parent"          android:layout_height="wrap_content"          />  
public void Onmoreclick () {viewstub viewstub = (viewstub) Findviewbyid (R. ID. View_stub); if (viewstub! = null) {View Inflatedview = viewstub. Inflate(); EditExtra1 = (EditText) inflatedview. Findviewbyid(R. ID. Edit_EXTRA1); EditExtra2 = (EditText) inflatedview. Findviewbyid(R. ID. Edit_EXTRA2); EDITEXTRA3 = (EditText) inflatedview. Findviewbyid(R. ID. Edit_EXTRA3); }  }

Tips:viewstub the layout that is loaded is not allowed to use tags, so it is possible that there is an unnecessary nesting structure in the loaded layout.

Learn more from Guo Shen blog, see:

http://blog.csdn.net/guolin_blog/article/details/42238627

[Android Advanced]android performance optimization

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.