[Android] Android development optimization-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. Private static Resources mResources; @ Overrideprotected void onCreate (Bundle state) {super. onCreate (state); if (mResources = null) {mResources = this. getResources () ;}} the 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 collection. 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) 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. Private static Resources mResources; @ Overrideprotected void onCreate (Bundle state) {super. onCreate (state); if (mResources = null) {// mResources = this. getResources (); mResources = this. getApplication (). getResources () ;}here set this. modify 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) Timely disabling resource Cursor is a class for managing data sets obtained by Android after querying data. 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. Cursor cursor = null; try {cursor = mContext. getContentResolver (). query (uri, null); if (cursor! = Null) {cursor. moveToFirst (); // process data} catch (Exception e) {e. printStatckTrace () ;}finally {if (cursor! = Null) {cursor. close () ;}} captures exceptions and closes cursor in finally. Similarly, when using files, close them in time. 4) use Bitmap to call recycle () in a timely manner as described in the previous chapter. If you do not use a Bitmap object, 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) The following example shows how to optimize the Adapter by constructing the BaseAdapter of ListView. The BaseAdapter class provides the following methods: 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 the ListView. The following is a complete sample code of the getView () method. 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 conver TView;} 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" 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. Www.2cto.com. 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.

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.