Analysis of Android development optimization: Tips for code optimization

Source: Internet
Author: User

Generally, programs are written under the pressure of the Project Plan. The Code completed at this time can complete the specific business logic, but the performance is not necessarily optimized. Generally, excellent programmers constantly rebuild the code after writing the code. There are many advantages of refactoring, one of which is to optimize the code to improve the performance of the software. The following describes the code optimization in the Android development process from several aspects.

1) Memory leakage caused by static variables

During code optimization, we need to pay special attention to static variables in the code. A static variable is a class-related variable. its lifecycle is declared from this class, and the class will be completely recycled by the garbage collector. Therefore, in general, static variables always occupy the memory space from the beginning of the class where they are used until the program exits. If you do not pay attention to it, static variables reference resources that occupy a large amount of memory, which may result in a waste of memory because the Garbage Collector cannot recycle the memory.

Let's take a look at a piece of code, which defines an Activity.

Copy codeThe Code is as follows: private static Resources mResources;

@ Override

Protected void onCreate (Bundle state ){

Super. onCreate (state );

If (mResources = null ){

MResources = this. getResources ();

}

}

This Code contains a static Resources object. Code snippet mResources = this. getResources () initializes the Resources object. In this case, the Resources object has reference to the current Activity object, and the Activity references all objects on the whole page.

If the current Activity is re-created (such as screen switching, the entire Activity is re-created by default), because Resources references the Activity created for the first time, this will prevent the Activity created for the first time from being recycled by the garbage collector, so that all objects in the Activity created for the first time cannot be recycled. At this time, some of the memory is wasted.

Experience Sharing:

In actual projects, we often add some object references to the set. If the set is static, pay special attention to it. When you do not need an object, you must promptly clear its reference from the collection. Alternatively, an update policy can be provided for the set to update the entire set in a timely manner. This ensures that the size of the set does not exceed a certain value and avoids the waste of memory space.

2) use the Context of the Application

In Android, the life cycle of the Application Context is as long as that of the Application, rather than dependent on the life cycle of an Activity. If you want to keep a long-lived object that requires a Context, you can use the Application object. You can call Context. getApplicationContext () or Activity. getApplication () to obtain the Application object.

Take the above Code as an example. You can modify the code as follows.

Copy codeThe Code is as follows: private static Resources mResources;

@ Override

Protected void onCreate (Bundle state ){

Super. onCreate (state );

If (mResources = null ){

// MResources = this. getResources ();

MResources = this. getApplication (). getResources ();

}

}

Modify this. getResources () to this. getApplication (). getResources (). After modification, some Resources objects have Application object references. If the Activity is re-created, the Activity created for the first time can be recycled.

3) Close resources in time

Cursor Is a class used to manage data sets after data is queried by Android. Normally, if we do not close it, the system will close it when it is recycled, but this is very inefficient. If the queried data volume is relatively small, if the Cursor data volume is very large, especially if Blob information exists, memory problems may occur. Therefore, you must disable Cursor in time.

The following is a common code snippet Using Cursor.

Copy codeThe Code is as follows: Cursor cursor = null;

Try {

Cursor = mContext. getContentResolver (). query (uri, null, null );

If (cursor! = Null ){

Cursor. moveToFirst ();

// Process data

}

} Catch (Exception e ){

E. printStatckTrace ();

} Finally {

If (cursor! = Null ){

Cursor. close ();

}

}

Capture exceptions and disable cursor in finally.

Similarly, when using files, close them in time.

4) use Bitmap to promptly call recycle ()

As mentioned in the previous chapter, when a Bitmap object is not used, you need to call recycle () to release the memory and set it to null. Although calling recycle () does not guarantee immediate release of occupied memory, it can accelerate the release of Bitmap memory.

During code optimization, if you find that a Activity uses a Bitmap object but does not explicitly call recycle () to release the memory, you need to analyze the code logic and add relevant code, call recycle () to release the memory after Bitmap is no longer used.

5) Optimize the Adapter

The following uses the BaseAdapter used to construct the ListView as an example to illustrate how to optimize the Adapter.

The following methods are provided in the BaseAdapter class:

Copy codeThe Code is as follows: public View getView (int position, View convertView, ViewGroup parent)

When each item in the ListView list is displayed, the getView method of the Adapter is called to return a View,

To provide the required View object to ListView.

The following is a complete sample code of the getView () method.

Copy codeThe Code is as follows: public View getView (int position, View convertView, ViewGroup parent ){

ViewHolder holder;

If (convertView = null ){

ConvertView = mInflater. inflate (R. layout. list_item, null );

Holder = new ViewHolder ();

Holder. text = (TextView) convertView. findViewById (R. id. text );

ConvertView. setTag (holder );

} Else {

Holder = (ViewHolder) convertView. getTag ();

}

Holder. text. setText ("line" + position );

Return convertView;

}

Private class ViewHolder {

TextView text;

}

When you scroll up the ListView, The getView () method is called repeatedly. The second parameter of getView () convertView is the View object in the cached List entry. When the ListView slides, getView may return the original convertView directly. ConvertView and ViewHolder are used here to make full use of the cache to avoid repeated creation of View objects and TextView objects.

If there are only a few ListView entries, this technique cannot improve the performance. However, if there are hundreds or even thousands of entries, this technique will only create several convertView and ViewHolder (depending on the number of entries that can be displayed on the current interface ), the performance difference is very big.

6) code "micro-optimization"

The current era has entered the "micro-era ". Here, "micro-optimization" refers to the code-level details optimization, that is, the overall structure of the Code is not changed, and the original logic of the program is not changed. Although Android uses the Dalvik virtual machine, traditional Java code optimization techniques are also applicable in Android development.

The following is a brief example. Generally, Java developers can understand it and do not describe specific code.

Creating new objects requires additional memory space. try to reduce the number of objects created.

Minimize the visibility of classes, variables, methods, and so on.

For String concatenation, use StringBuffer instead of String.

Do not declare temporary variables in the loop or catch exceptions in the loop.

If there are no requirements for thread security, try to use a collection object with thread insecurity.

Use a collection object. If you know its size in advance, you can set the initial size in the constructor.

To read files, you must use a cache class to close the files in time.

Use exceptions with caution. Exceptions may cause performance degradation.

If the program frequently creates threads, you can consider using the thread pool.

Experience Sharing:

There are a lot of things about code optimization, from a variable declaration to an algorithm. Especially in the code Review process, you may repeatedly Review whether the code can be optimized. However, I think the microoptimization of code is very time-consuming and there is no need to optimize all the code from start to end. Developers should optimize some code according to the specific business logic. For example, some methods may be called repeatedly in an application, so this part of code is worth special optimization. For other code, developers should pay attention to it during code writing.

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.