Memory Cache for Android memory optimization and android Memory Optimization

Source: Internet
Author: User

Memory Cache for Android memory optimization and android Memory Optimization
Preface:The above two blogs have talked about the basic knowledge of images and image loading methods and optimization. All these optimizations are designed to avoid the OOM problem in applications. A good application should not only be robust and error-free, but also be convenient for users. For users, your application should not only be beautiful but also smooth, and be quickly presented to them. Soon loading images requires caching in addition to loading optimization. The following blog will describe image caching.What is cache?The principle of caching technology is to regard all objects accessed by users as a complete set, mark through algorithms which objects are frequently accessed by users, and put these objects into a set. This set is a complete set, when the next user accesses the object, the user will first search for the object to be accessed from this subset. if the object is found, the user will directly return the object. If the object is not found, the user will search for the object in the complete set. Of course, what I'm talking about here is just a matter of principle. There are many algorithms in cache, and there are more than one level of cache, so I will not talk about it here.Why cache?If files are cached, you do not have to read files from the source address every time, saving both time and traffic. Frequent access to network resources, especially on mobile devices, will consume a lot of user traffic and power, which is intolerable to users. Therefore, no matter which aspect of the application, the cache must be added.What are the image caches in Android? What are their characteristics?There are two types of image caching for Android devices: Memory caching, image caching in device memory, external caching, and image caching on disk, the disk can be an internal storage space or an external SD card. These two caches have their own advantages. The advantage of the memory cache is that it is fast. The disadvantage is that it also consumes memory because it is read into the memory, so it cannot be too large, you need to consider the allocated space when using it. Another drawback is that the space will disappear after the application is restarted. The advantage of the external cache is that it can store a large amount of data for a long time (compared with the memory cache). The disadvantage is that it is slow.Memory Cache:On the Android official website, we recommend using LruCache as the memory cache. LruCache is actually a LinkedHashMap (Supplement: LinkedHashMap is a list of two-way loops and does not support thread security, lruCache encapsulates it and adds thread-safe operations), which stores a certain number of objects with strong references. Each time a new object is added, it is in the head of the linked list, when the allocated space is used up, the objects at the end are removed, and the removed objects can be recycled by gc. Note the capacity of LruCache. This capacity cannot be too large, cause OOM, and cannot be too small. The google website provides the following comments for reference:

  • When allocating the LruCache size, consider the remaining memory of your application;
  • How many images are displayed on the screen at a time, and how many images are cached for display;
  • Considering the resolution and size of your mobile phone and the number of images cached in the same way, the larger the dpi, the larger the memory required by your mobile phone. I will explain this in my blog;
  • The image resolution and pixel quality also determine the memory usage;
  • What is the frequency of image access? Are some images frequently accessed? If yes, you can use multiple lrucaches for caching and allocate them to different lrucaches Based on the Access frequency;
  • How to balance the quality and quantity of a piece, sometimes you can consider caching low-resolution images, and then request higher quality images in the background when used;
In short, the size of the LruCache you allocate cannot be too large or too small. You need to consider it comprehensively in the application. The following code uses LruCache as an example:
Private LruCache <String, Bitmap> mMemoryCache; // declare the cache space final int maxMemory = (int) (Runtime. getRuntime (). maxMemory ()/1024); // obtain the maximum memory allocated by the application in the system // allocate 1/8 of the application memory as the cache space final int cacheSize = maxMemory/8; mMemoryCache = new LruCache <String, Bitmap> (cacheSize) {@ Override protected int sizeOf (String key, Bitmap bitmap) {// Override the sizeOf method, the number of bytes occupied by the returned image, instead of the number of images. Each time an image is added, return bitmap is called. getByteCount ()/1024 ;}};
Note: Some may ask the following code:
intcacheSize=4*1024*1024;// 4MiB  LruCachebitmapCache=newLruCache(cacheSize){      protectedintsizeOf(Stringkey,Bitmapvalue){          returnvalue.getByteCount();  }}

The calculation of the two sizeOf values is different. The purpose of this method is to return the cache space occupied by the image instead of the number of images, and the unit of this value is the same as that of cacheSize. Summary:Based on the above explanation, you need to know the following knowledge when using the memory cache LruCache:
  • LruCache encapsulates LinkedHashMap and provides the LRU (Least Recently Used uses the algorithm at Least Recently) cache function;
  • LruCache uses the trimToSize method to automatically delete the least recently accessed key-value pairs;
  • LruCache does not allow null key values, and javashashmap does;
  • The LruCache thread is secure, and the LinkedHashMap thread is not secure;
  • When inheriting LruCache, the sizeOf method must be rewritten to calculate the size of each entry. In put and get, safeSizeOf (K key, V value), safeSizeOf (K key, V value), and sizeOf (K key, V value) are called ), this method returns 1 by default.

 

Public interest platform: coder_online (coder_online) allows you to obtain original technical articles and become a friend of java/C ++/Android/Windows/Linux, exchange programming experience online, obtain basic programming knowledge, and solve programming problems. Programmer InterAction alliance, developer's own home.

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.