Analyzing Android Development Optimization: Tips for optimizing from a code perspective

Source: Internet
Author: User

Below we will learn from several aspects of the Android development process of code optimization, the need for a friend reference under

Usually we write programs that are done under the pressure of the project plan, where the finished code can complete the specific business logic, but performance is not necessarily optimal. In general, good programmers constantly refactor the code after they have written the code. There are many benefits to refactoring, one of which is to optimize the code to improve the performance of the software. Let's look at several aspects of code optimization in the Android development process.

1) memory leaks due to static variables

In the process of code optimization, we need to pay special attention to the static variables in the code. A static variable is a class-dependent variable whose life cycle is declared from this class, and the class is completely reclaimed by the garbage collector before it is destroyed. Therefore, in general, static variables from the beginning of the class being used will always occupy the memory space until the program exits. If you are not aware that a static variable refers to a resource that consumes a lot of memory, causing the garbage collector not to reclaim memory, it can cause a waste of memory.

Let's start with a piece of code that 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 ();

}

}


There is a static resources object in this piece of code. The code fragment Mresources = This.getresources () initializes the resources object. The resources object then has a reference to the current Activity object, and the activity references all the objects in the entire page.

If the current activity is recreated (for example, the entire activity is recreated by default), because the resources reference the activity that was created for the first time, the activity created for the first time will not be recycled by the garbage collector. This causes all objects in the activity that were created for the first time to not be recycled. At this point, some of the memory is wasted.

Experience Sharing:

In actual projects, we often add references to some objects to the collection, and if the set is static, you need to pay special attention. When you don't need an object, be sure to clean up its references from the collection in a timely manner. Or you can provide an update policy for the collection, update the entire collection in a timely manner, so that the size of the collection does not exceed a certain value, avoiding wasted memory space.

2) using the application context

In Android, the life cycle of the application context is as long as the lifetime of the application, rather than depending on the life cycle of an activity. If you want to keep a long-lived object, and the object needs a context, you can use the Application object. You can get the application object by calling the Context.getapplicationcontext () method or the Activity.getapplication () method.

Still take the above code as an example. You can modify the code to look like the following.

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 ();

}

}


Here This.getresources () is modified to This.getapplication (). Getresources (). When modified, the resources object has a reference to the Application object. If the activity is recreated, the activity that was created for the first time can be recycled.

3) Close resources in a timely manner

The cursor is a class of management data collection that is obtained after the Android query data. Normally, if we do not close it, the system shuts down when it is recycled, but this is particularly inefficient. If the amount of data the query gets is small, it's okay if the cursor has a very large amount of data, especially if there's blob information in it, a memory problem can occur. So be sure to close the cursor in time.

A generic code fragment using the cursor is given below.

Copy CodeThe code is as follows:
cursor cursor = NULL;

try{

cursor = Mcontext.getcontentresolver (). query (Uri,null,null,null,null);

if (cursor! = NULL) {

Cursor.movetofirst ();

Working with Data

}

} catch (Exception e) {

E.printstatcktrace ();

} finally {

if (cursor! = NULL) {

Cursor.close ();

}

}


That is, the exception is captured and the cursor is closed in finally.

Similarly, when using the file, you should also close it in time.

4) use bitmap to call recycle () in time

As mentioned in the previous section, when you do not use the bitmap object, you need to call recycle () to free memory and then set it to null. Although calling recycle () does not guarantee immediate release of the memory consumed, it can speed up the release of bitmap memory.

In the process of code optimization, if you find that an activity uses the bitmap object, but does not explicitly call recycle () to free memory, you need to parse the code logic, add the relevant code, and call Recycle () to free memory after you no longer use bitmap.

5) Optimization of the adapter

The following is an example of constructing a ListView baseadapter to illustrate how to optimize 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, adapter's GetView method is called to return a view,

To provide the desired view object to the ListView.

The following is a code example of the complete 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;

}


The GetView () method is called repeatedly when the ListView is scrolled up. The second parameter of GetView () Convertview is the View object in the list entry that is cached. When the ListView is sliding, the GetView may return to the old Convertview directly. Convertview and Viewholder are used here to take full advantage of the cache and avoid creating view objects and TextView objects over and over again.

If the ListView has only a few entries, this technique does not yield much performance gains. But if there are hundreds of or even thousands of entries, using this technique will only create a few Convertview and Viewholder (depending on the number of entries the current interface can display), the performance difference is very great.

6) Code "micro-optimization"

Today's era has entered the "micro-era". "Micro-optimization" here refers to the code level of detail optimization, that is, do not change the overall structure of the code, does not alter the original logic of the program. Although Android uses Dalvik virtual machines, traditional Java code optimization techniques are also applicable in Android development.

The following is a brief list of the parts. Because the average Java developer is able to understand, no specific code instructions are made.

Creating new objects requires additional memory space to minimize the creation of new objects.

Modify the visibility of classes, variables, methods, and so on to a minimum.

For concatenation of strings, use StringBuffer instead of string.

Do not declare temporary variables in the loop, do not catch exceptions in loops.

If there is no requirement for thread safety, try to use a thread-unsafe collection object.

Using a Collection object, you can set the initial size in the construction method if you know its size beforehand.

File read operations need to use the cache class to close the file in a timely manner.

Caution with exceptions, using exceptions can cause performance degradation.

If your program creates threads frequently, you might consider using a thread pool.

Experience Sharing:

The micro-optimization of the code has a lot of things to say, as small as a variable declaration, large to an algorithm. Especially in the process of code review, it is possible to repeatedly review whether the code can be optimized. But I think that the micro-optimization of the code is very time-consuming and it is not necessary to optimize all the code from start to finish. Developers should optimize for specific parts of the code based on their business logic. For example, there may be some methods in the application that will be called repeatedly, then this part of the code is worthy of special optimization. Other code needs to be noticed by the developer in the process of writing the code.

Analyzing Android Development Optimization: Tips for optimizing from a code perspective

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.