Memory Optimization in Android

Source: Internet
Author: User
Tags deprecated xml parser

Memory leaks can cause a lot of problems:
1. Slow response time (the JVM virtual opportunity triggers the GC frequently when memory consumption is high)
2. Inexplicable disappearance (when your program takes up more memory, it is more likely to get killed in the background.) Conversely, the smaller the memory footprint, the longer it will exist in the background)
3. Direct Crash (OutOfMemoryError)
Android memory facing problems:
1. Limited heap memory, original only 16M
2. Memory size consumption, etc. depending on the device, operating system level, screen size and different
3. The program cannot be controlled directly
4. Support background multitasking (multitasking)
5. Running on top of a virtual machine
I have optimized Android memory primarily through the following 5 aspects (5R):
1.Reckon (computing) The first thing you need to know about the memory consumed by your app is the ability to Baizhanbudai
2.Reduce (less) consumes less resources
3.Reuse (Reuse) when the first use is finished, try to give other use
4.Recycle (Recycle) return resources to production flow
5.Review (check) Review your program to see what is wrong with the design or code.
Here are a few things to say in detail:
First, reckon (calculation)
It is necessary to understand the memory usage of your application. If memory usage is too high, it needs to be optimized because less memory can reduce the chance that Android systems will terminate our process, and it can improve multitasking execution efficiency and experience. Here are a few ways to view and calculate memory usage from the system memory (systems RAM) and heap memory (heap) Two:
1.System RAM (System memory):
Observe and calculate the memory usage of the system, you can use Android to provide us with two tools procstats,meminfo. They have a memory usage that focuses on the background, and the other is memory usage at runtime.
(1) Process Stats:
Android 4.4 KitKat proposed a new system service called Procstats. It will help you better understand the memory usage of your app in the background (background).
Procstats can monitor your app's behavior over time, including how long it's been running in the background and how much memory was used during that time. This helps you quickly find inefficient and irregular areas of your application to avoid affecting their performs, especially when running on low-memory devices.
You can use the ADB shell command to procstats (adb shell Dumpsys procstats–hours 3), or the more convenient way to run the Process Stats developer tool (click Settings in the 4.4 version of the phone) > Developer options > Process Stats)

Click on a single entry to view more information
(2) Meminfo:
Android also provides a tool called Meminfo. It calculates the memory usage of each process according to the PSS standard (proportional Set size--actual physical memory) and sorts it by importance.
You can do it via the command line: (adb shell Dumpsys meminfo) or use the device to click Settings > Apps > Running (not with procstats, it can also run on older versions)
2.Heap (heap memory):
In the program you can use the following methods to query memory usage
(1) Activitymanager#getmemoryclass ()
Querying the limits of available heap memory, 3.0 (Honeycomb) can request more heap memory by largeheap= "true" (though this counts as "cheating")
(2) Activitymanager#getmemoryinfo (Activitymanager.memoryinfo)
The resulting memoryinfo can be viewed in the following field properties:
Availmem: Indicates system remaining memory
Lowmemory: It is a Boolean value that indicates whether the system is running in low memory
Hreshold: It means low memory runs when the system has less memory left
(3) Android.os.debug#getmemoryinfo (Debug.memoryinfo memoryinfo)
The resulting memoryinfo can be viewed in the following field properties:
Dalvikprivatedirty:the private dirty pages used by Dalvik.
Dalvikpss:the proportional set size for Dalvik.
Dalvikshareddirty:the shared dirty pages used by Dalvik.
Nativeprivatedirty:the private dirty pages used by the native heap.
Nativepss:the proportional set size for the native heap.
Nativeshareddirty:the shared dirty pages used by the native heap.
Otherprivatedirty:the private dirty pages used by everything else.
Otherpss:the proportional set size for everything else.
Othershareddirty:the shared dirty pages used by everything else.
Dalvik: Refers to the memory used by the Dalvik.
Native: Is the memory used by the native heap. It should refer to the memory allocated on the heap using c\c++.
Other: Refers to memory used in addition to Dalvik and native. But what exactly does it mean? Include at least non-heap memory allocated in c\c++, such as memory allocated on the stack.
Private: Refers to proprietary. Non-shared.
Share: Refers to shared memory.
PSS: Physically used physical memory (proportional allocation of memory consumed by shared libraries)
Privatedirty: It refers to the size of the memory that is unshared and cannot be paged out (can not be paged to disk). For example, the small object that Linux buffers in order to increase memory speed, even if your process ends, the memory will not be released, it just back into the buffer.
Shareddirty: Referring to Privatedirty I think it should mean the size of the memory that is shared and cannot be paged out (can not be paged to disk). For example, the small object that Linux buffers in order to increase the allocated memory speed, even if all the processes that share it end, the memory is not released, it just goes back to the buffer.
(4) Android.os.debug#getnativeheapsize ()
Returns the total memory size of the current process navtive heap itself
(5) Android.os.debug#getnativeheapallocatedsize ()
Returns the amount of memory used in the current process navtive heap
(6) Android.os.debug#getnativeheapfreesize ()
Returns the amount of memory already remaining in the current process navtive heap
(7) Memory Analysis Tool (MAT):
Often memory leak analysis is considered a difficult task, typically performed by a team of experienced people. However, today we are going to introduce the MAT (Eclipse Memory Analyzer) is considered to be a "fool-like" Heap Dump file analysis tool, you only need a click of the mouse to generate a professional analysis report.
Such as:

Reduction (reduction) is mainly used to reduce memory usage by the following methods:
(a) Bitmap:
Bitmap is a large memory consumption, the vast majority of oom crashes are generated when operating bitmap, the following to see how several ways to handle the picture:
(1) Image display: To load the size of the image according to the needs. For example, when the thumbnail is loaded in the list only for previews (thumbnails), the entire picture is displayed only when the user clicks on the specific item to see the details
(2) Image size: Direct use of ImageView display bitmap will occupy more resources, especially when the picture is large, may cause crashes. Using Bitmapfactory.options to set up insamplesize, this reduces the need for system resources. The property value insamplesize indicates that the thumbnail size is one of a fraction of the original picture size, that is, if the value is 2, the width and height of the thumbnail being taken are 1/2 of the original picture, and the image size is 1/4 of the original size.
(3) Image pixel: There are four kinds of images in Android, namely:
Alpha_8: Consumes 1byte of memory per pixel
argb_4444: Consumes 2byte of memory per pixel
argb_8888: Consumes 4byte of memory per pixel (default)
rgb_565: Consumes 2byte of memory per pixel
Android default color mode for argb_8888, this color mode color is the most delicate, showing the highest quality. But the same, the memory is also the largest. So use rgb_565 (no transparency), or argb_4444 (with transparency) in cases where the picture is not particularly high
(4) Image recycling: After using bitmap, it is necessary to call the Bitmap.recycle () method in a timely manner to free up the memory space occupied by the bitmap and not wait for the Android system to release.
(5) Catch exception: After these optimizations there is also the risk of oom, so the following need a final level-capture Oom exception
(b) Modify the object reference type:
The reference is divided into four levels, which are four levels from highest to lowest: Strong reference > Soft reference > Weak reference > Virtual reference.
If you just want to avoid the occurrence of outofmemory exceptions, you can use soft references. If you are more concerned about the performance of your application and want to reclaim some objects that occupy large memory as soon as possible, you can use weak references.
Starting with the Android2.3 version (API level 9), the garbage collector is more focused on the recovery of soft/weak references, which are deprecated for soft-referencing or weak-referencing bitmap caching schemes.
(iii) Other methods of reducing memory use
(1) Use the static final modifier for constants
(2) static method instead of virtual method
(3) Reduction of unnecessary global variables
(4) Avoid creating unnecessary objects
(5) Avoid internal getters/setters
(6) Avoid using floating-point numbers
(7) Using the solid analogy interface good
(8) free use of enumerations
(9) For loop, access member variable is much slower than accessing local variable, never call any method in the second condition of for, For-each syntax introduced in java1.5 (for example, Foo A:marray) The compiler also generates an additional store operation for local variables in each loop (such as the variable A in the example above), which is 4 bytes more than the normal loop, which is slightly slower
(10) Understanding and using class libraries
Third, reuse (reuse)
Reuse is one of the important ways to reduce memory consumption, the core idea is to reuse existing memory resources to avoid creating new, the most typical use is caching (cache) and pool.
(a) Bitmap cache: The bitmap cache is divided into two types: the memory cache and the hard disk cache.
Memory Cache (LruCache):
The memory cache provides fast bitmap access at the expense of valuable application memory. The system-provided LRUCache class is ideal for use as a caching bitmap task, storing the most recently referenced objects in a strongly referenced linkedhashmap, and releasing objects that have not been used recently since the cache exceeds the specified size.
Note: Previously a very popular memory cache implementation was a softreference (soft reference) or WeakReference (weak reference) bitmap caching scheme, but it is deprecated. Starting with the Android2.3 version (API level 9), the garbage collector focuses more on the recovery of soft/weak references, which makes the above scenario quite ineffective.
Hard disk cache (Disklrucache):
A memory cache is very helpful for speeding up access to recently browsed bitmap, but you cannot limit the images available in memory. The GridView component, which has a larger dataset, can easily consume memory caches. Your app may be interrupted while performing other tasks, such as making a call, and the task in the background may be killed or the cache released. Once the user has re-focused (resume) to your app, you have to process each picture again.
In this case, the hard disk cache can be used to store the bitmap and reduce the time (number of times) the picture is loaded after the picture is freed by the memory cache. Of course, loading a picture from a hard disk is slower than memory and should be done in a background thread because the hard disk read time is unpredictable.
Note: If you are accessing pictures very often, contentprovider may be more appropriate to store cached images, such as image gallery applications. For more information on memory caching and hard disk caching, see the official Google Tutorials https://developer.android.com/develop/index.html
(ii) Image caching for open source projects:
The cache for pictures is now inclined to use open source projects, here I list a few I have searched for:
1. Android-universal-image-loader Picture Cache
The most widely used image caches are currently available, supporting most of the features of mainstream image caches.
Project Address: Https://github.com/nostra13/Android-Universal-Image-Loader
2. Picasso Square Open-source image cache
Project Address: Https://github.com/square/picasso
Characteristics:
(1) can automatically detect the reuse of adapter and cancel the previous download
(2) Image transformation
(3) Local resources can be loaded
(4) You can set up a placeholder resource
(5) Support Debug mode
3. Imagecache image cache, including memory and SDcard cache
Project Address: Https://github.com/Trinea/AndroidCommon
Characteristics:
(1) Support pre-fetching new picture, support waiting queue
(2) contains level two cache, customizable file name save rule
(3) selectable multiple cache algorithms (FIFO, LIFO, LRU, MRU, LFU, MFU, etc.) or a custom cache algorithm (13)
(4) Easy to save and initialize the recovery data
(5) Support for different types of network processing
(6) can initialize the cache according to the system configuration, etc.
4. Android network communication Framework Volley
Project Address: Https://android.googlesource.com/platform/frameworks/volley
When we need to communicate with the network in the program, the general use of Things is asynctaskloader,httpurlconnection,asynctask,httpclient (Apache), in 2013, Google i/ o Volley was released. Volley is a network communication library on the Android platform that makes network communication faster, simpler, and more robust.
Characteristics:
(1) Asynchronous download of JSON, image, etc.;
(2) Ordering of network requests (scheduling)
(3) Priority processing of network requests
(4) Cache
(5) Multi-level cancellation request
(6) Linkage with activity and life cycle (simultaneous cancellation of all network requests at end of activity)
(iii) Adapter adapter
Adapter is widely used in Android, especially in the list. So adapter is the "Distributing center" of data, so it is necessary to make memory optimization for it. Primarily use Convertview and viewholder for cache processing
(d) Pond (pool)
1. Object pool:
The basic idea of using object pooling is to save the used objects, and then reuse them again the next time you need them, to some extent reducing the overhead of creating objects frequently. Not all objects are suitable for pooling-because maintaining the object pool also costs a certain amount of money. When you pool objects that are not very expensive at build time, you may have a situation where the "cost of maintaining the object pool" is greater than the "cost of generating new objects", which results in degraded performance. But for the objects with considerable overhead, pooling technology is an effective strategy to improve the performance.
2. Thread pool:
The basic idea of the thread pool is also the idea of an object pool, which opens up a memory space in which many (not dead) threads are stored, and the thread execution schedule is handled by the pool manager. When a thread task is taken from a pool, the threads object is pooled after execution, which avoids the performance overhead of repeatedly creating thread objects and saves system resources.
For example: An application to work with the network, there are many steps need to access the network, in order not to block the main thread, each step to create threads, in-line and network interaction, with the thread pool is simple, the thread pool is a package of threads, make the thread easier to use, only need to create one thread pool, Put these steps into a thread pool like a task, as long as you call the Destroy function of the thread pool when the program is destroyed. Java provides the Executorservice and executors classes that we can apply to create thread pools.
(v) Note: To use the cache as appropriate, because of limited memory. You can save the path address do not store image data, not often used to try not to cache, when not on the empty.
Iv. Recycle (recycling)
Recycling can be said to be the most important part of memory usage. Because memory space is limited, no matter how you optimize, how to save memory total useful time. The point of recycling is to clean up and release the memory resources and memory space that are unused and obsolete.
(a) garbage collection (GC):
1. Java Garbage Collector:
Java technology provides a system-level thread, the garbage collector thread (garbage Collection thread), to track each piece of allocated memory space, and when the Java Virtual machine (Java VM) is in an idle loop, The garbage collector thread automatically checks each allocated memory space, and then automatically reclaims every unused chunk of memory that can be recycled.
2. Function:
1. Clear unused objects to free up memory:
2. Eliminate fragmentation of heap memory space:
3. Advantages of garbage collector:
1. Reduce the burden of programming and improve efficiency:
2. It protects the integrity of the program:
4, Garbage collector disadvantage:
1. Resource-intensive time:
2. Unpredictable:
3. Uncertainties:
4. Not operable
5. Finalize ():
Each object has a Finalize method, which is inherited from the object class.
This method is called by the object's garbage collector when garbage collection determines that no more references to the object exist.

Java technology allows the use of the Finalize method to do the necessary cleanup before the garbage collector clears objects from memory. Once the garbage collector is ready to release the space occupied by the object, its finalize () method is called first, and the memory occupied by the object is actually reclaimed when the next garbage collection action occurs.
It is simple to say that the Finalize method is called before the garbage collector deletes the object.
6, System.GC ():
We can call the System.GC method and recommend that the virtual machine be garbage collected (note that it is recommended, but the virtual opportunity does not work like this, and we cannot predict!). )
In summary, in the Java language, there are only two criteria that determine whether a piece of memory space conforms to the garbage collector collection:
1. A null value was given to the object, and the following has not been called.
2. A new value is assigned to the object, and the memory space is redistributed.
Finally, again, a memory space that meets the collection criteria of the garbage collector does not necessarily mean that the memory space will be collected by the garbage collector.
(ii) Recovery of resources:
1. Thread (threads) Recycling:
No GC can be recycled for anything involved in a thread (anything reachable by a thread cannot is GC ' d), so threads can easily cause memory leaks. Because a running thread is one of the garbage collected root (GC Roots) objects, it is not garbage collected. When the garbage collector determines whether an object is accessible, it always uses the garbage collection root object as the reference point.
2. Cursor (cursor) Recovery:
The cursor is a class of managed data collection that is obtained after the Android query data, after the use is finished. You should ensure that the memory that the cursor occupies is released in a timely manner, rather than waiting for the GC to handle it. And Android is obviously prone to the programmer manually close the cursor, because in the source code we find that if we wait for the garbage collector to recycle, the user will be given an error.
In one case, we can't just close the cursor, which is the case in CursorAdapter, but notice that CursorAdapter does not automatically close the cursor at the end of the acivity, so You need to close it manually in the OnDestroy function.
(iii) receiver (receiver) recovery
Unregisterreceiver () was not called after calling Registerreceiver ().
When we use the Registerreceiver () method in our activity to register the Broadcastreceiver, be sure to call the Unregisterreceiver () method during the activity's lifetime to unregister
This means that the registerreceiver () and Unregisterreceiver () methods must appear in pairs, and usually we can rewrite the activity's Ondestory () method to unregister
(iv) Stream/file (flow/file) Recycling:
Mainly for various streams, file resources and so on, such as:
Inputstream/outputstream,sqliteopenhelper,sqlitedatabase,cursor, files, I/o,bitmap pictures and other operations should be remembered to show off.
V. Review (INSPECTION)
The main purpose is to check the code for the unreasonable and can improve the place
(a) Code Review (Codes check):
Code review primarily checks for some of the unreasonable or improved optimizations that exist in the codes.
(ii) UI Review (view check):
Android will consume a lot of resources and memory for layout rendering of controls in the view, so this is part of what we need to be aware of.
1. Reduce the view level:
Reducing the view level can effectively reduce memory consumption because the view is a tree structure, and each refresh and rendering is traversed once.
1.hierarchyviewer: To reduce the view level you need to know the view level first, so here's a handy tool hierarchyviewer that comes with the SDK.
You can find it at the following address: \sdk Path\sdk\tools

As you can see, hierarchyviewer can see the hierarchy of the current view very clearly, and can see the execution efficiency of the view (small dots on the view, green means smooth, yellow and red followed), So we can easily see which view may affect our performance to further optimize it.
2.ViewStub Label
This label can make the UI in special cases, the visual effect is similar to setting the view's invisibility, but its greater meaning is that the views wrapped by this tag will not occupy any memory space by default.
3.include Label
This tab allows you to load external XML directly into the current structure and is a common label for reusing UI resources.
4.merge Label
It plays an important role in optimizing the UI structure. The goal is to optimize the structure of the entire Android layout by cutting redundant or extra layers.
5. Layout with Java code faster than writing in XML
In general, the layout of the Android program is often written using XML files, which can improve the development efficiency, but in view of the security of the Code and execution efficiency, can be created through Java code, although the Android compiled XML is binary, But the efficiency of loading an XML parser is much more efficient for resource use, and Java processing is a lot faster than XML, but for a complex interface to write, it may require some nesting considerations, and if you're flexible, it's a better way to use Java code to lay out your Android application.
3. Reusing system resources:
1. Using the system-defined ID
To reference the system ID in the XML file, simply add the "@android:" prefix. If you are using system resources in Java code, you are basically the same as using your own resources. The difference is that you need to use Android. The R class uses the system's resources rather than the R class specified by the application.
2. Using the system's picture resources
The advantage of this is that the artist does not need to repeat a copy of the existing picture, can save a lot of work hours, the other is to ensure that our application style and system consistent.
3. Using the system's string resources
If you use a system string, the multilanguage environment is already supported by default. For example, the direct use of @android:string/yes and @android:string/no, in the Simplified Chinese environment will show "OK" and "Cancel", in English environment will show "OK" and "Cancel".
4. Use the style of the system
Suppose there is a textview in the layout file that displays the title of the window, using a medium-sized font. You can use the following code snippet to define the style of the TextView.

Memory optimization in Android

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.