Android performance optimization and data optimization methods _android

Source: Internet
Author: User

Android performance optimization-layout optimization

Today, continue Android performance optimization with a coded detail optimization.

Coding details, for the operation of the efficiency of the program also has a lot of impact. Today this topic because of the limited technical ability, so also dare not in the deep to share. I divide this topic into the following sections:

(1) Cache

(2) data

(3) Deferred loading and priority loading

1> Cache

Caching in Android can be used in a number of places: objects, IO, networks, DB, and so on. Object caching 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) Picture caching

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

Load picture-> To determine if there is a-> exists in the cache, directly remove settings to ImageView-> does not exist, then request the network download pictures-> picture Download success, the picture cache, set to ImageView

There are a lot of 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 is not changed frequently

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

(3) ListView Cache

ListView item data Cache, I believe we are more clear. is to use the GetView method of adapter class to convertview the principle of reuse, create viewholder to realize reuse. The Material design also provides recyclerview to replace the ListView. It will force you to use Viewholder view in adapter.

(4) Message caching

The message here refers to messages sent in handler. The system provides us with a obtainmessage () rifle 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
static message obtain () {
 synchronized (spoolsync) {
 if (sPool!= null) {message
  m = spool;
   spool = M.next;
  M.next = null;
  m.flags = 0; Clear In-use flag
  spoolsize--;
  return m;
 }
 }
 return new Message ();
}

In the above code, spool is a cached message instance, first judging that if it is not NULL, take it directly, or else create a new message instance.

(5) IO cache

In Java, we provide some IO streams with caching policies:

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

2> data

The optimization of data storage can be divided by data type and structure.

(1) Use StringBuilder or stringbuffer to stitch strings to reduce the temporary allocation of objects. The difference between StringBuilder and StringBuffer is actually one thing: under concurrent operations, StringBuffer is thread-safe. The advantages and disadvantages of thread safety also lead to a decrease in execution speed. So, if you're not in a multithreaded operation, use StringBuilder. Both the StringBuilder and StringBuffer constructors allow you to pass in an order of magnitude to initialize its space size. Thus, a certain amount of space can be allocated to conserve memory resources.

(2) using WeakReference. The benefits of weak references must be clear to all. Especially in devices with limited memory space such as Android, it is important to allocate and release memory. A typical scenario used by WeakReference is handler. It is clear 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 executes for a long time, the activity or fragment needs to be freed (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, it will lead to activity or fragment can not be effectively released, resulting in its resources can not be released, the result is conceivable: Oom. So the solution to this problem is to use WeakReference or to define handler as static. Here's how to use WeakReference:

Private final MyHandler MyHandler = new MyHandler (this);
private static class MyHandler extends Handler {
 private final weakreference 
 

The code is very simple, that is, put the fragment in the WeakReference. The view is operated directly in the Handlemessage.

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

(1) ArrayList for the data query faster, LinkedList for data insertion and deletion speed than ArrayList faster.

(2) Linkedhashmap can remember the order in which the data is stored, HashSet does not allow duplicate elements to exist. The data in the Weakhashmap can be automatically recycled by the system GC at the right time, suitable for the memory-tight scenario.

(3) The Collections tool class also provides a number of collections that are suitable for multi-threaded operations and improves performance , such as:

(4) Android system also provides better performance data types, such as: Sparsearray,sparsebooleanarray,sparseintarray,pair. The sparse key is of type int. Two-point search and simple array storage are used. And does not require the overhead of a generic conversion, which is more performance-friendly than a map.

3> Delay Loading

The use of deferred loading in Android is also widespread, such as delayed loading of fragment data in Viewpager. Because Viewpager the default is to initialize both content. So we need to handle the delay loading.

Similarly, time-consuming operations are not performed on time-sensitive functions in activity or fragment. Avoid the occurrence of ANR anomalies.

Java provides a scheduledxecutorservice as a deferred load, in fact, the timer timer delay is a bug exists. So it is not recommended to use a timer. Hon Yang Blog has a bug about the timer: Timer flaw

Android can use some of the handler methods to delay operations:

(1) postdelayed

(2) Postattime

(3) sendmessagedelayed

And the view of the Postdelayed,alarmmanager timing and so on.

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.