Android Memory optimized memory cache

Source: Internet
Author: User

What is a cache?

The principle of caching technology is to treat all objects accessed by the user as a complete set, which is an algorithm that marks the objects that the user accesses frequently, and puts the objects into a set, which is a subset of the complete works. The next time the user accesses the object, it will first look up the subset of objects that the user wants to access, and then return to the object if they find it, and then find it in the complete set if it is not found. Of course, what I'm talking about here is the original reason, the cache is a lot of algorithms, and there are more than one level of cache, here is more than speak.

Why use a cache?

If you have a cache, you can save time and traffic by not having to read the files from the source address every time. In particular, mobile devices, frequent access to network resources will consume a lot of users of traffic and power, which is not tolerated by users, so regardless of which aspect of the application must be added to the cache.

What are the image caches in Android? What are the characteristics of each?

The image cache of Android device is divided into two kinds, one is memory cache, picture is in memory of device, one is external cache, picture is cached on disk, disk can be internal storage space or external SD card. These two caches each have each advantage, the memory cache advantage is fast, the disadvantage is because also reads into the memory so also will consume the memory, therefore cannot be too big, uses the time to consider allocates the space, also has one disadvantage is after the application restarts disappears. The advantage of an external cache is that it can hold large amounts of data for long periods of time (compared to memory caches), and the downside is slow.

Memory Cache:

In Android It is recommended to use LRUCache as the memory cache, LRUCache is actually a linkedhashmap (supplementary knowledge: Linkedhashmap is a two-way loop list, does not support thread safety, LRUCache It has been encapsulated to add a thread-safe operation), which holds a certain number of object strong references, each time the addition of new objects are in the head of the linked list, when the allocated space is exhausted when the end of the object is removed, the removed object can be collected by GC. Here you need to pay attention to the capacity of LRUCache, this capacity can not be too large, will cause oom, not too small, do not play the role of caching. Google's website gives a view as a reference:

• When assigning LRUCache size, consider how much of your application's remaining memory is.

• How many images are displayed on a single screen, and how many images are cached for display;

• Consider the resolution and size of your phone, cache the same number of images, the larger the DPI of the phone will require more memory;

• Image resolution and pixel quality also determine the size of the memory occupied;

• How often do images are accessed, are there some images that are frequently accessed? If present you can consider using multiple · LRUCache to do the cache, according to the frequency of access to different lrucache;

• How to balance a piece of quality and quantity, sometimes you can consider caching low-resolution images, when used to request higher quality images in the background;

In short, you allocate the size of the LRUCache can not be too large, but also not too small, specific to the application you have to consider comprehensively.

The following code is an example of using LRUCache:

1 privatelrucache<string, bitmap> mmemorycache;//declaring cache space

2 Finalint maxmemory = (int) (Runtime.getruntime (). MaxMemory ()/1024);//Gets the maximum memory allocation for the application in the system

3//Allocate 1/8 of application memory as cache space

4 Finalint cacheSize = MAXMEMORY/8;

5 mmemorycache= New lrucache<string, bitmap> (cacheSize) {

6 @Override

7 Protectedint sizeOf (String key, Bitmap Bitmap) {

8//Rewrite the sizeof method, return the number of bytes occupied by the picture instead of the number of pictures, each time the picture is added will be called

9 Returnbitmap.getbytecount ()/1024;

10}

11};

Note: Some students may ask the following code:

1 Intcachesize=4*1024*1024;//4mib

2 Lrucachebitmapcache=newlrucache (cacheSize) {

3 protectedintsizeof (Stringkey,bitmapvalue) {

4 Returnvalue.getbytecount ();

5}

6}

The calculations for these two sizeof are not the same, as explained here, the purpose of this method is to return the image to occupy the cache space instead of the number of pictures, and this value is the same unit as CacheSize.

Summarize:

In this tutorial, you need to know the following when using memory cache LRUCache:

The LRUCache encapsulates the LINKEDHASHMAP, providing the ability to cache the LRU (leastrecently used least recently used algorithm);

LRUCache automatically deletes the most recently accessed key-value pairs by means of the TrimToSize method;

LRUCache does not allow null key values, Linkedhashmap allowed;

LRUCache thread security, linkedhashmap thread is unsafe;

When inheriting LRUCache, the sizeof method must be replicated to calculate the size of each entry. When put and get are called safesizeof (k key, V value), safesizeof (k key, Vvalue) will call SizeOf (k key, V value), this method returns 1 by default.

In addition, we recommend a third-party testing tool to detect all aspects of the app: http://www.ineice.com/

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android Memory optimized memory cache

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.