Android performance optimization: Talk bitmap memory management and optimization

Source: Internet
Author: User

Recently, in addition to those busy with project development, I am currently preparing my paper. Short time did not write the blog, tonight is rare to summarize. Just a little bit of time. So, in order to make it work, yes. Nagging, go straight to the chase.

Engaged in the development of Android self-mobile terminal, presumably is often to deal with memory problems, talking about the memory problems encountered in Android development, such as bitmap such as eating a large amount of memory is very easy to deal with an oom, of course, There are already many well-known open-source images loaded into the framework, such as: Imageloader. Picasso and so on, these frameworks have been able to overcome the oom problem caused by bitmap very well, even though these frameworks can save a lot of developers ' valuable time. But there is a situation. Very many people just start to learn simply to invoke the interface provided by these frameworks, is asked to the framework of some of the implementation of the principle, is basically a blank in the brain. From my point of view, I feel that assuming that we can master some of the principles of the framework, presumably the significance of the application of tuning is very significant, today, mainly to talk about. Assuming there is no picture loading frame, how do we deal with Bitmap's memory problem?
When it comes to bitmap, we may want to start with some basic knowledge about bitmap memory allocations in Android virtual machines and give the following paragraph on Google's site

The general meaning is to say. Prior to Android3.0, bitmap's memory allocation was divided into two parts, part of which was allocated in Dalvik's VM heap. The memory of the pixel data is allocated in the native heap, and after the Android3.0. The bitmap memory is already allocated on the VM heap. The difference between these two distributions is that the memory of the native heap is not managed by the Dalvik virtual machine. We want to release bitmap memory and must call the Recycle method manually. and to the Android 3.0 platform, we will be able to bitmap memory completely assured to the virtual machine management, we just need to ensure that the bitmap object adhere to the virtual machine GC Root Tracing recycling rules can be. Ok. Basic knowledge of science to this. Here are a few points to talk about how to optimize bitmap memory issues.

1.Bitmap Reference counting method (for the optimization of the platform prior to Android3.0, first demo Code)

Private intMcacherefcount =0;//Cache reference CountersPrivate intMdisplayrefcount =0;//Display reference counter...//The current bitmap is displayed on the UI interface Public void setisdisplayed(Booleanisdisplayed) {synchronized( This) {if(isdisplayed)            {mdisplayrefcount++; mhasbeendisplayed =true; }Else{mdisplayrefcount--; }} checkstate ();}//Whether the token is cached Public void setiscached(Booleaniscached) {synchronized( This) {if(iscached)        {mcacherefcount++; }Else{mcacherefcount--; }} checkstate ();}//used to detect if bitmap has been recycledPrivate synchronized void CheckState() {if(Mcacherefcount <=0&& Mdisplayrefcount <=0&& mhasbeendisplayed && Hasvalidbitmap ()) {Getbitmap (). Recycle (); }}Private synchronized Boolean Hasvalidbitmap() {Bitmap Bitmap = Getbitmap ();returnBitmap! =NULL&&!bitmap.isrecycled ();}

The example code above, which uses the method of reference counting (Mdisplayrefcount and Mcacherefcount) to track whether a bitmap is currently displayed or is in the cache. Recycle bitmap When the following conditions are met:
Both Mdisplayrefcount and Mcacherefcount have a reference count of 0.
Bitmap is not NULL, and it has not been recycled.

2. Using the cache, LRUCache and disklrucache combination
About LRUCache and Disklrucache, we certainly will not be unfamiliar (friends who have doubts can go to the API website search LRUCache, and Disklruccache can take a look at this Good article: Disklrucache use introduction), For performance and app considerations, we're sure to be able to cache images in memory and SD cards after the first time we've loaded them from the network. In this way, we do not have to go to the network to load images, in order to very good control of memory problems, you will consider using LRUCache as bitmap in memory storage container, the SD card uses Disklrucache to manage the image cache on the disk uniformly.

combination of 3.SoftReference and Inbitmap parameters
It is mentioned in the 2nd that it is possible to use LRUCache as a container for storing bitmap, while in LRUCache there is a method worth noting, that is entryremoved, according to the document, This method is called when the LRUCache container is full of objects that need to be phased out to make room for them ( note. This is simply the object being eliminated from the LRUCache container, but does not mean that the object's memory will be immediately Dalvik by the virtual machine to be recycled, this method will bitmap use softreference wrapped up, Use a pre-prepared hashset container to store the bitmap that will be recycled. Someone will ask. What is the point of storing this? The reason for this is that it is also necessary to refer to the Inbitmap (before Android3.0, the details of the bitmapfactory.options parameter information in the API). This reference is primarily provided to us for bitmap in the multiplexed memory, assuming that this parameter is set and the following conditions are met:

    • Bitmap must be variable, that is, the inmutable setting must be ture;
    • Android4.4 The following platform, you need to ensure that the inbitmap and will be decode to get the bitmap of the size of the same specifications;
    • Android4.4 and above the platform, only need to meet the size of the inbitmap to decode to get bitmap size specifications can be;

When the above conditions are met. When the system decoder the picture, it checks if there is a reusable bitmap in memory. Avoid our frequent to the SD card upload into the picture and result in system performance degradation, after all, from the direct memory from the re-use of the SD card than the efficiency of the IO operation to increase dozens of times times. Write too much text. The following is a couple of demo code

Set<softreference<bitmap>> Mreusablebitmaps;PrivateLrucache<string, bitmapdrawable> Mmemorycache;//used to put out the bitmap by LRUCache eliminationif(Utils.hashoneycomb ()) {mreusablebitmaps = Collections.synchronizedset (NewHashset<softreference<bitmap>> ());} Mmemorycache =NewLrucache<string, bitmapdrawable> (mcacheparams.memcachesize) {//LRUCache is called when the object is retired, used to reuse bitmap in memory, improving the performance of loading pictures    @Override    protected void entryremoved(BooleanEvicted, String key, Bitmapdrawable OldValue, bitmapdrawable newvalue) {if(RecyclingBitmapDrawable.class.isInstance (OldValue)) {(recyclingbitmapdrawable) oldValue). setiscached (false); }Else{if(Utils.hashoneycomb ()) {Mreusablebitmaps.add (NewSoftreference<bitmap> (Oldvalue.getbitmap ())); }        }    }....}Private Static void addinbitmapoptions(Bitmapfactory.options Options, Imagecache Cache) {//Set inmutable to one of the conditions in effect True,inbitmapOptions.inmutable =true;if(Cache! =NULL) {//try to find bitmap that can be reused in memoryBitmap inbitmap = cache.getbitmapfromreusableset (options);if(Inbitmap! =NULL) {options.inbitmap = Inbitmap; }    }}//Gets the bitmap that currently satisfies the reuse condition, returns the bitmap if it exists, returns null if it does not existprotectedBitmapGetbitmapfromreusableset(Bitmapfactory.options Options) {Bitmap Bitmap =NULL;if(Mreusablebitmaps! =NULL&&!mreusablebitmaps.isempty ()) {synchronized(Mreusablebitmaps) {Finaliterator<softreference<bitmap>> Iterator = Mreusablebitmaps.iterator (); BITMAP item; while(Iterator.hasnext ()) {item = Iterator.next (). get ();if(NULL! = Item && item.ismutable ()) {if(Canuseforinbitmap (item, options))                        {bitmap = Item; Iterator.remove (); Break; }                }Else{Iterator.remove (); }            }        }    }returnBitmap;}//Infer if the conditions for using Inbitmap are metStatic BooleanCanuseforinbitmap (Bitmap candidate, bitmapfactory.options targetoptions) {if(Build.VERSION.SDK_INT >= build.version_codes. KITKAT) {///Android4.4 start, the multiplexed bitmap size specification is greater than or equal to the required decoding specifications to meet the reuse conditions        intwidth = targetoptions.outwidth/targetoptions.insamplesize;intHeight = targetoptions.outheight/targetoptions.insamplesize;intByteCount = width * Height * getbytesperpixel (candidate.getconfig ());returnByteCount <= Candidate.getallocationbytecount (); }///Android4.4 must meet the required bitmap size specifications of the reused bitmap and the requested uniform ability to be reused    returnCandidate.getwidth () = = Targetoptions.outwidth && candidate.getheight () = = Targetoptions.outheight && Targetoptions.insamplesize = =1;}

4. Reduction of sample rate, Insamplesize calculation
I believe that we will not be unfamiliar with the insamplesize, so there is no longer to do too much introduction, about reducing the sample rate of Insamplesize calculation method. I see a lot of algorithms online. The following algorithm should be the best algorithm, also consider the kind of wide difference between the height of the picture (such as: panorama) processing.

 Public Static int calculateinsamplesize(Bitmapfactory.options Options,intReqwidth,intReqheight) {//Raw height and width of image        Final intHeight = options.outheight;Final intwidth = options.outwidth;intInsamplesize =1;if(Height > Reqheight | | width > reqwidth) {Final intHalfheight = height/2;Final intHalfwidth = width/2; while(halfheight/insamplesize) > Reqheight && (halfwidth/insamplesize) > Reqwidth) {Insamplesize *=2; }LongTotalpixels = width/insamplesize * height/insamplesize;Final LongTotalreqpixelscap = reqwidth * Reqheight *2; while(Totalpixels > Totalreqpixelscap) {Insamplesize *=2; Totalpixels/=2; }        }returnInsamplesize;

5. Use Decodefiledescriptor to encode pictures (temporary does not know the principle. Welcome to Master Guidance Maze)
The use of decodefiledescriptor to deal with pictures can save memory. I tried it while I was writing the code. Do want to save memory than other Decode method, inquire the explanation on the net. Not very clear, I saw some of the source code can not make a thing, why use such a way can save some of the memory, assuming there is a clear principle of the master. Welcome to answer my doubts .

To this, the bitmap processing of several optimization points have been analyzed to complete, for now, perhaps everyone in the development process used to use the framework to load the picture, so do not care about the image memory processing related issues, suppose you want to know some optimization bitmap memory principle or want to make a good picture loading frame. I hope this article will give you a little bit of thought. If the reader feels that the article is wrong, please criticize it in the comments below.

Copyright notice: This article blog original article. Blogs, without consent, may not be reproduced.

Android performance optimization: Talk bitmap memory management and 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.