Android performance optimization one data optimization

Source: Internet
Author: User

In my previous blog, I discussed with you Optimized details of the operation of the SQLite database in Android. Not yet seen click here:

Android Performance optimization-layout optimization

Today, continue Android Performance Optimization one coding detail optimization .

The coding details have a lot of effect on the running efficiency of the program. Today this topic because of technical ability is limited, so also dare not in the deep to share with you. I will divide this topic into the following subsections:

(1) Cache

(2) data

(3) Lazy loading and priority loading

1> Cache

The cache in Android can be used in a lot of places: objects, IO, network, DB, etc... The object cache can reduce the memory allocation, the IO cache can read and write access to the disk, the network cache can reduce the access to the network, the DB cache can reduce the operation of the database.

Caching-oriented scenarios are also evident in Android development:

(1) Image cache

The LRUCache caching mechanism is available in Android. We can use LRUCache to cache images. The cache processing steps for a picture are generally:

Load picture---to determine if there is a cache exists, the direct removal of the settings to ImageView, does not exist, the request network download picture, picture download succeeded, the picture cache, set to ImageView

There are many good third-party open source libraries in Android, so we don't have to reinvent the wheel. For example: Fresco (Facebook products), Picasso, Glide, UIL.

(2) data that does not change frequently

For data that doesn't need to change frequently, such as some product categories in the app. We can cache it. You don't have to ask the network to load the data every time. This is easier to understand, not much to say.

(3) Cache for ListView

The cache of the ListView item data is very clear to everyone. is to make use of the principle of Convertview multiplexing in the GetView method of the adapter class to create a Viewholder implementation multiplexing. Recyclerview is also available in Material Design to replace the ListView. It will force you to use Viewholder in the adapter view.

(4) Message caching

The message here is the one sent in handler. The system provides us with a obtainmessage () to use a message. Let's look at the source code:

/*** Return A new Message instance from the global pool. Allows US to* Avoid allocating new objects in many cases. */Public StaticMessageobtain() {    synchronized(Spoolsync) {        if(SPool!= NULL) {            Messagem= SPool;            SPool= m.Next;            m.Next= NULL;            m.Flags= 0; //Clear In-use flag            spoolsize--;            returnm;        }    }    return newMessage();}
in the above code, spool is a cached message instance, first of all, if it is not NULL, take it directly, or create a new message instance.

(5) IO cache

In fact, Java provides us with some IO streams with cache policy:

BufferedReader, BufferedWriter. Use this type of IO stream instead of InputStream, Reader and OutputStream, writer, and so on.

2> data

Optimizations for data storage can be divided from data types and structures.

(1) Use StringBuilder or stringbuffer to stitch strings, reducing the temporary allocation of objects. The difference between StringBuilder and StringBuffer is one thing: under concurrent operations, StringBuffer is thread-safe. There are pros and cons, and thread safety also leads to a slowdown in execution. So, if not in the case of multithreaded operation, use StringBuilder. Both the StringBuilder and StringBuffer constructors allow you to pass in an order of magnitude to initialize its space size. This allows you to allocate a certain amount of space and conserve memory resources.

(2) Use WeakReference. The benefits of weak references must be clear to all. Especially in devices with limited memory space for Android, it is important to allocate and release memory. A typical scenario for weakreference use is handler. It is well known that the use of handler in activity or fragment is generally implemented as an internal class. This can cause a problem. If a task in handler takes a long time, the activity or fragment needs to be released (Ondestory) because the message associated with handler has not been completed. At this time handler can not be released, because handler and activity or fragment association, then will lead to activity or fragment can not be effectively released, eventually resulting in their resources can not be released, the result is imagined: Oom. So, the solution to this problem is to use WeakReference or define handler as static. Here 's how to use WeakReference:

Private FinalMyHandlerMyHandler= NewMyHandler( This);private Static ClassMyHandlerextendsHandler{   Private FinalWeakReference<homefragment>m;    PublicMyHandler(homefragmenthomefragment){      m= NewWeakReference<homefragment> (homefragment);   }   @Override   Public voidHandlemessage(Messagemsg) {      homefragmenthomefragment= m.Get();         if(homefragment!= NULL) {         homefragment.Vpbanner.Setcurrentitem(msg.arg1);;      }   }}
The code is simple enough to put fragment in the WeakReference. Remove the view directly from the Handlemessage.

There are more data structures, such as ArrayList and LinkedList, Linkedhashmap and HashSet, and Weakhashmap.

(1) ArrayList for data query speed is relatively fast,linkedlist for data insertion and deletion faster than ArrayList.

(2) linkedhashmap can remember the order in which data is deposited, HashSet does not allow duplicate elements to exist.

(3) The Collections Tool class also offers a number of collections suitable for multi-threaded operations, and improves performance, for example:

(4) Android system also provides a better performance data type, such as: Sparsearray,sparsebooleanarray, Sparseintarray,pair. The sparse key is of type int. Binary lookup and simple array storage are used. And without the overhead of a generic conversion, the performance is better than the map.

3> Lazy Loading

Lazy Loading in Android is also more widely used, such as lazy loading of fragment data in Viewpager. Because the Viewpager default is to initialize both contents. So we need to deal with deferred loading.

Similarly, you do not take time-consuming actions in activity or fragment-sensitive functions. Avoid the occurrence of ANR anomalies.

Java provides the scheduledxecutorservice as a lazy load, in fact, timer timer delay is a bug exists. Therefore, it is not recommended to use a timer. Hon Yang Blog has a bug about the timer: a timer defect

Some methods of handler can be used in Android to delay operations:

(1) postdelayed

(2) Postattime

(3) sendmessagedelayed

And the Postdelayed,alarmmanager timing of the view.

About the data optimization, this blog will first and everyone to share here, welcome everyone to make mistakes, shoot brick building ~

Android performance optimization one data optimization

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.