Smart Android performance optimization using soft references and weak references to optimize memory usage

Source: Internet
Author: User

Objective:

Android developers know that the memory usage of mobile devices is a very sensitive topic, today we look at how to use soft references and weak references to optimize memory usage. Here are a few concepts to understand.

1.StrongReference (Strong reference)

Strong reference is one of our most common, generally we in the code directly through the new object, and so on, are strong references, strong references as long as the existence is not destroyed, the memory will not be reclaimed by the system. Let's take the example of generating bitmap as follows:

Bitmap Imagebitmap = Readbitmapfromresource (Getresources (), r.mipmap.bg_post_activity_5);

Generate Bitmap Code:

     Public int Resourcesid) {        new  bitmapfactory.options ();         return Bitmapfactory.decoderesource (Resources, resourcesid, options);    }
2.SoftReference (soft reference)

Soft references are used to describe useful but not necessary objects that can be reclaimed by the system if the memory is critically low, and if the object is likely to be used frequently, use soft references as much as possible. Therefore, this is a good way to solve the problem of oom, and this feature is well suited for caching: such as Web caching, image caching, and so on. Here's an example of caching bitmap:

New softreference<bitmap>= Softreference.get ();
3.WeakReference (Weak reference)

Weak references are also used to describe non-essential objects, and when the JVM is garbage collected, the objects associated with the weak references are reclaimed, regardless of memory adequacy, and the strength of the weakreference is significantly lower than softreference, so if the object is more likely to not be used, You can use a weak reference. Also, take the cache bitmap as an example:

New weakreference<bitmap>= Weakreference.get ();
4.PhantomReference (Virtual Reference)

A virtual reference differs from the previous soft reference and weak reference, and it does not affect the life cycle of the object. If an object is associated with a virtual reference, it can be reclaimed by the garbage collector at any time, as with no reference to it. Also, take the cache bitmap as an example:

New Referencequeue<bitmap>(); Phantomreference<Bitmap>  new phantomreference<bitmap>= Phantomreference.get ();
5. Several references are recycled concept tests

From the above analysis, we can see that the probability of memory being reclaimed by the system from small to large is: Virtual reference-weak reference-soft reference-strong reference , we write a program to verify.

 Public classMainactivityextendsappcompatactivity {PrivateLinearLayout request_layout; PrivatePhantomreference<bitmap>phantomreference; PrivateWeakreference<bitmap>WeakReference; PrivateSoftreference<bitmap>SoftReference; PrivateBitmap strongreference; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Request_layout=(LinearLayout) Findviewbyid (r.id.request_layout); Findviewbyid (R.ID.REQUEST_BTN). Setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {testreference ();    }        }); }    Private voidtestreference () {//Simulate memory usage add ImageView to a layout to simulate memory usageImageView ImageView =NewImageView ( This); Bitmap Imagebitmap=Readbitmapfromresource (Getresources (), r.mipmap.bg_post_activity_5);        Imageview.setimagebitmap (IMAGEBITMAP);        Request_layout.addview (ImageView); if(Strongreference = =NULL) {strongreference=Readbitmapfromresource (Getresources (), r.mipmap.bg_post_activity_5); } LOG.E ("Reference", "strongreference---->" +strongreference); if(SoftReference = =NULL) {SoftReference=NewSoftreference<bitmap>(Readbitmapfromresource (Getresources (), r.mipmap.bg_post_activity_5)); } Bitmap Bitmap=Softreference.get (); LOG.E ("Reference", "softreference---->" +bitmap); if(WeakReference = =NULL) {WeakReference=NewWeakreference<bitmap>(Readbitmapfromresource (Getresources (), r.mipmap.bg_post_activity_5)); } Bitmap Bitmap1=Weakreference.get (); LOG.E ("Reference", "weakreference---->" +bitmap1); if(Phantomreference = =NULL) {Referencequeue<Bitmap> queue =NewReferencequeue<bitmap>(); Phantomreference =NewPhantomreference<bitmap>(Readbitmapfromresource (Getresources (), r.mipmap.bg_post_activity_5), queue); } Bitmap bitmap2=Phantomreference.get (); LOG.E ("Reference", "phantomreference---->" +bitmap2); }     PublicBitmap Readbitmapfromresource (Resources resources,intResourcesid) {bitmapfactory.options Options=Newbitmapfactory.options (); returnBitmapfactory.decoderesource (Resources, resourcesid, options); }}

First click to print information:

The printed information can be reclaimed directly by a virtual reference, or it can be said that there is no reference directly.

Click to print the message more than once:

In the case of more and more tense simulation memory use, and did not appear to recycle the weak reference, and then recycle the soft reference, but two are recycled, in fact, according to the Java Normal reference order is stronger than the weak reference, but from the Android 2.3 (API level 9), The garbage collector is more inclined to reclaim objects holding soft or weak references, which makes soft references less reliable like weak references. So the picture cache no longer uses the LRU algorithm with soft references. But strong references have always been perseverance.

Summarize:

From the above introduction and test comparison can be learned that if we are more concerned about the performance of the app, we can use a soft or weak reference to what is not commonly used and memory-intensive objects to do cache processing, in view of the insurance, you can choose to use weak or soft reference, The probability of the two being recovered is comparable.

Smart Android performance optimization using soft references and weak references to optimize memory usage

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.