Memory optimization for app performance optimization

Source: Internet
Author: User

This paper is the learning note, video address (http://www.imooc.com/video/13670) of the course "Memory optimization of App performance optimization" in Mu-class network.

# # How do I see the memory allocation of an app in Android?
Method One:
1. Launch Android Studio and virtual machine to establish a connection.
2. Open the cmd window and enter the ADB shell.
3. Enter PS.

4. You can see that there is a process named application package name, this is the process in which our app is located

5. In order to see the memory usage of the app's process in detail, enter Dumpsys Meminfo + package name.

Method Two:

 float total_memory= Runtime.getruntime () .totalmemory () * 1.0f/1024/1024 .getruntime () .freememory () *1.0f/1024/ 1024.getruntime () .maxmemory () * 1.0f/1024/1024              
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

Method Three:
Turn on Android Monitor for Android studio.
Method Four:
Open Android Studio's tools→android→android Device Monitor.

How to allocate and recycle Android memory
    1. An app is usually a process that corresponds to a virtual machine.
    2. The GC (garbage collector) triggers garbage collection only when there is insufficient space left in the heap. (When the garbage heap remains low after GC garbage collection, the GC initiates a system request, and if the GC has many variables, GC recycling consumes processor time, and if the processing time is long, it affects the app response).
    3. When the GC is triggered, all threads are paused, and in extreme cases thread jitter occurs (which is later said).
App Memory throttling mechanism
    1. The maximum memory limit allocated per app varies by device. viewing mode: '
ActivityManager manager= (ActivityManager)getSystemService(ACTIVITY_SERVICE);int memory=manager.getMemoryClass();int large=manager.getLargeMemoryClass();//大部分情况下二者相同
    • 1
    • 2
    • 3
    1. Eat large Memory: Pictures
Background app cleanup mechanism when switching apps
    • LRU Cache (LRU algorithm, most recently used at the top, least likely to be cleared) when the app is switched
    • The ontrimmemory (int level) method of the activity in the application is recalled when the system cleans up (or memory changes). At this point we can determine whether the system memory is not enough, if it is to clean up some of the application of unused memory to make the application of memory smaller, reduce the possibility of being cleaned out by the system. Level corresponding information
App Memory Optimization method
  • Data structure Optimization
    1. Frequent string concatenation takes the form of StringBuilder instead of the + (which produces useless intermediate string memory blocks, the total time spent in the video splicing the same string is 3ms and 8000ms!!! )。
    2.arraymap,sparsemap Replace HashMap (HashMap inefficient, high memory consumption).
    3. Memory Jitter (improper use of variables, such as the sudden generation of a lot of variables or to apply for a lot of memory space, but soon finished things abandoned, after a while to do the above, if the heap is not enough, GC triggered garbage collection, at this time all threads paused, memory usage will be as high as jitter and low).
    4. The smaller class also consumes 0.5KB.
    Each entry of 5.HASHMAP requires an additional 32B.
  • Object Reuse
    1. Reuse the resources that the system comes with.
    Convertview multiplexing of 2.listview/gridview (Viewholder).
    3. Avoid performing object creation in the OnDraw method (Onmeasure is also called multiple times and is recommended within the Onsizechanged method).
  • Avoid memory leaks
    Memory leaks: Because of a code flaw, this memory is stopped, but is still referenced by other things, causing the GC to be unable to reclaim it.
    1. Memory leaks can cause fewer remaining heap, and GC fires frequently. (In the video, click the start thread in the activity (simple hibernation 5 minutes), then exit into the activity, start the thread, repeat multiple times, then go to Android Device Monitor, click Cause GC to start GC recycle, It is found that the count of Byte-array is reduced, repeating the above operation, and the value of count stop decreasing is increasing, indicating a memory leak occurred. The reason is that the thread is a custom inner class that implicitly references the activity object, and that the line is executed in 5min, which improves if you change to sleep for a short time. workaround : Put it in service execution).
    2. In particular, activity leaks
    3. Use application context instead of activity context (which may often exit), some view such as dialog must be activity context (Token).
    4.Cursor objects should be closed in time.
1.OOM problem analysis of oom problem optimization
    • The inevitability and resolution of oom is not to be mentioned.
    • Most of Oom takes place in pictures.
The meaning of strong references and soft references

Strong references are the usual way of writing.
The use of soft references. (virtual reference is similar to it)

Private map<string, softreference<bitmap>> Imagecache =New hashmap<string, softreference<bitmap>> ();PublicvoidAddbitmaptocache (String path) {A strongly referenced Bitmap object Bitmap Bitmap = bitmapfactory.decodefile (path);Soft-Referenced Bitmap object softreference<bitmap> softbitmap =new softreference<bitmap> (Bitmap); //weakreference<bitmap> weakbitmap=new weakreference<bitmap> (BITMAP); Translateanimation animation; //Add the object to the map so that it caches imagecache.put (path, softbitmap);} public Bitmap getbitmapbypath (String path) {//Bitmap object that takes soft references from the cache softreference<bitmap> Softbitmap = Imagecache. get (path); //determine if there is a soft reference if (softbitmap = =  NULL) {return null;} //Remove Bitmap object, if due to insufficient memory bitmap is recycled, will get empty return softbitmap.< Span class= "Hljs-keyword" >get (); }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21st
    • 22
    • 23
    • 24

Consider the following scenario: Some member variables are not used after several times, but still occupy the memory space, they are recycled as the activity is destroyed, even if GC triggers garbage collection will not be recycled, you can put them in softreference, put and read see the above code, The GC can be recycled when it triggers a garbage collection.

2. Ways to optimize the oom problem
    • Optimization of temporary bitmap

1.bitmapfactory.options class

Bitmapfactory. Options options = new Bitmapfactory;options.injustdecodebounds = True; Bitmapfactory.decoderesource (Getresources (), R.yin,options) ;//not directly loaded, Get bitmap picture width height bitmapfactory.insamplesize = Scale; Bitmap bitmap1=bitmapfactory.decoderesource (Getresources (), R.drawable.yin,options2" ;// The larger the scale, the more blurry the image, and the smaller the amount of memory             
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
//RGB_565让ARGB只占两个字节,大小缩小一倍,且变化不明显BitmapFactory.Options options=new BitmapFactory.Options();        options.inPreferredConfig= Bitmap.Config.RGB_565;Bitmap bitmap1=BitmapFactory.decodeResource(getResources(),R.drawable.yin,options);
    • 1
    • 2
    • 3
    • 4
    • 5
The Bitmapregiondecoder class can achieve range selection picture Details Bitmapregiondecoder Decoder=bitmapregiondecoder. newinstance (,false); Bitmapfactory= new bitmapfactory =decoder.decoderegion ( new Rect (Width/2-SCREEN_WIDTH /2+shiftpx, Height/2-screen_height/2,width/2 +screen_width/2+SHIFTPX, height/< Span class= "Hljs-number" >2+screen_height/2), options2);    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

2. Pass the soft reference. The advantage is that the system can be recycled when the memory is low, the drawback is that there is no priority for recycling, it may not be recycled, but will be displayed.

PublicClass Bitmapcache {StaticPrivate Bitmapcache Cache;Private arraymap<string,mysoftre> Hashref;After the soft reference is recycled, the object is collected and you can see which ones are recycled.Private referencequeue<bitmap> queue;PrivateBitmapcache () {hashref=New Arraymap<> (); Queue=New Referencequeue<> (); }/* Inherit softreference so that each instance has an identifiable identity */PrivateClass Mysoftre extends softreference<bitmap>{Private String key="";PublicMysoftre (Bitmap referent, referencequeue<? Super Bitmap> q,string key) {super (referent, q);This.key=key; } }PublicStatic BitmapcacheGetInstance () {if (cache==NULL) {cache=New Bitmapcache (); }return cache; }/* References an instance of a bitmap object in a soft-reference manner and saves the reference */PublicvoidAddcachebitmap (String key, Bitmap Bitmap) {Cleancache (); Mysoftre msf=New Mysoftre (Bitmap,queue,key); Hashref.put (KEY,MSF); }Public BitmapGetbitmap (String key) {Bitmap bitmap=null; try {if (Hashref.containskey (key)) {Mysoftre msf=hashRef.< Span class= "Hljs-keyword" >get (key); BITMAP=MSF. get (); return bitmap;} catch (NullPointerException e) {return null;} } private void cleanCache () { Mysoftre msf=null; while ((msf= (Mysoftre) queue.poll ())!=null) {HashRef.remove (Msf.key); }} public void clearCache () { Cleancache (); Hashref.clear (); System.GC (); System.runfinalization (); }} 
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21st
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66

3. Use the LRU Cache.

PublicClass MemoryCache {PrivateStatic final String tag="Jason";Linkedhashmap is designed to build LRU algorithms, but threads are unsafePrivate map<string,bitmap> cache= Collections.synchronizedmap (New Linkedhashmap<string, Bitmap> (8,0.75f,true));PrivateLong size=0;MemoryCache the size already allocatedPrivateLong limit=1000000;PublicMemoryCache () {Setlimit (Runtime.getruntime (). MaxMemory ()/4); }PrivatevoidSetlimit (Long l) {limit=l; LOG.D (TAG,"MemoryCache'll use up to" +limit/1024/1024+"MB"); }Public BitmapGet (String ID) {try {if (!cache.containskey (ID)) {ReturnNull }Return cache.Get (ID); }catch (NullPointerException e) {ReturnNull } }PublicvoidPut (String Id,bitmap Bitmap) {try {if (Cache.containskey (ID)) {size-=getsizeinbytes (cache.Get (ID)); } cache.put (Id,bitmap); Size+=getsizeinbytes (bitmap); Checksize (); }catch (Throwable th) {th.printstacktrace ();}}PrivatevoidChecksize () {log.i (TAG,"Cache size=" +size+"Length=" +cache.size ());if (size>limit) {iterator<map.entry<string,bitmap>> iterator=cache.entryset (). Iterator ();while (Iterator.hasnext ()) {map.entry<string,bitmap> entry=iterator.next (); size- =getsizeinbytes (Entry.getvalue ()); Iterator.remove (); if (size<=limit) {break;}} LOG.D (Tag, "clean cache,new size=" +cache.size ());}} private long getSizeInBytes ( Bitmap Bitmap) {if (Bitmap==null) { return 0;} return bitmap.getrowbytes () *bitmap.getheight ();} public void clear () {cache.clear () ; }}
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21st
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69

Memory optimization for app performance 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.