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

Source: Internet
Author: User

Usually we write programs that are done under the pressure of the project plan, where the completed code can complete the business logic, but the performance is not necessarily the most optimized. In general, a good programmer will continue to refactor the code after it has finished writing the code. There are many benefits to refactoring, one of which is to optimize the code to improve the performance of the software. Here are a few ways to learn about code optimization in the Android development process.

1) Static variable causes memory leak

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-related variable whose lifecycle is declared from this class to be destroyed by the garbage collector when it is completely reclaimed. So, in general, static variables start with the class being used to occupy the memory space until the program exits. If you are not aware that a static variable refers to a resource that consumes a large amount of memory, the garbage collector is unable to reclaim memory, which can result in a waste of memory.

Let's take a look at a piece of code that defines an activity.

Copy Code code 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 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 (such as a toggle, the entire activity is recreated by default), because resources references the activity created for the first time, the activity that was first created cannot be reclaimed by the garbage collector. This causes all objects in the activity that were created for the first time to be reclaimed. At this time, part of the memory is wasted.

Experience Sharing:

In actual projects, we often add references to objects to the collection, and if the set is static, it needs special attention. When you don't need an object, be sure to clear its references from the collection in time. Or you can provide an update policy for the collection, updating the entire collection in time to ensure that the size of the collection does not exceed a certain value, avoiding the waste of memory space.

2 Use the context of application

In Android, the lifecycle of the application context is as long as the lifecycle of the application, rather than depending on the lifecycle of an activity. You can use the Application object if you want to keep a long life object and the object needs a context. 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 Code code 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, modify the This.getresources () to This.getapplication (). Getresources (). After modification, the resources object has a reference to the Application object. If the activity is recreated, the first creation of the activity can be reclaimed.

3) Timely shutdown of resources

Cursor is a class that manages data collections after Android queries the data. Normally, if we do not close it, the system shuts down when it is recycled, but this is particularly inefficient. If the query gets a small amount of data, it's fine, if the amount of cursor data is very large, especially if there is blob information inside, there may be memory problems. So be sure to close cursor in time.

A generic code fragment using cursor is given below.

Copy Code code 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 ();

}

}


The exception is caught, and cursor is closed in finally.

Similarly, in the use of documents, but also in time to close.

4 use bitmap in time to call recycle ()

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

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

5) to optimize the adapter

The following example illustrates how to optimize adapter with the Baseadapter of the constructed ListView.

The following methods are available in the Baseadapter class:

Copy Code code as follows:

Public View GetView (int position, View Convertview, ViewGroup parent)

When each item in the ListView list is displayed, the adapter GetView method is invoked to return a view,

To provide the desired view object to the ListView.

The following is a code example of a complete GetView () method.

Copy Code code 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 scrolling up ListView, The GetView () method is called repeatedly. The second parameter of the GetView () Convertview is the view object in the cached list entry. When the ListView slides, the GetView may return directly to the old Convertview. Convertview and Viewholder are used here to make the most of the cache and avoid repeatedly creating view objects and TextView objects.

If there are only a few entries in the ListView, this technique does not provide much performance improvement. But if there are hundreds of or even thousands of entries, using this technique creates only a few Convertview and Viewholder (depending on the number of entries the current interface can display), and the performance difference is very large.

6 Code "micro-optimization"

Today's era has entered the "micro-era." Here the "micro-optimization" 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. While Android uses Dalvik virtual machines, traditional Java code optimization techniques are also available for Android development.

The following is a brief list of the parts. Because the general Java developers can understand, no longer do a specific code description.

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 the minimum.

For concatenation of strings, use StringBuffer instead of string.

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

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

Using collection objects, you can set the initial size in the constructor if you know their size in advance.

File read operations need to use the cache class to close the file in time.

Use exceptions with caution, and using exceptions can cause performance degradation.

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

Experience Sharing:

Code micro-optimization has a lot of things to say, small to a variable declaration, large to a section of the algorithm. Especially in the process of code review, it may be repeatedly reviewed whether the code can be optimized. However, I think that the code micro-optimization is very time-consuming, there is no need to optimize all the code from beginning to end. Developers should be tailored to a particular section of code based on specific business logic. For example, there may be some methods in the application 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 code.

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.