Memory management

Performance optimization overview:

About a month will be spent on 7-8 topics to share the experience accumulated in the work and study of Android performance optimization. I hope you’ll stay tuned.

Now for topic two: Memory optimization

But this is just to provide you with some ideas and a more comprehensive summary, not much, hope there are mistakes or questions in the comments below.

Finally, mind mapping and optimization framework will be sorted out after completion, please look forward to it. If the program crashes while running, or is suddenly killed by the system, you should read on.




Anroid Optimization (2)_ Memory optimization 2.png

This is the mind map for this chapter, but it is very compressed. Here is the sample, with the original and source linked at the bottom. It’s still worth downloading.




.

The vast majority of an application’s lifetime is spent processing data in memory, and while most of us are aware of the need to use as little memory as possible on our phones, not all of us are aware of the performance impact of memory usage. So, let’s talk about it.

First, talk about memory in mobile devices

  • No matter how much memory is allocated to the application, it will never be satisfied.

  • There are two big differences between mobile devices and traditional computers;

  • It is both common sense and experience to use as little memory as possible on a given device.

  • Performance depends on three factors (which we’ll cover below)

    • How does the CPU manipulate specific data types
    • How much storage is required for data and instructions

Two, use the appropriate data type

Using long is slower than short and int and using only double and mixing float and double is slower than using float alone.

Note: Since not all instructions are executed at the same time and the CPU is very complex, it is not possible to predict the exact time. Short arrays sort much faster than other types of arrays

Reason: Short uses count sort and the algorithm complexity is linear while int and long use quicksortCopy the code

Processing 64-bit types (long or double) is slower than processing 32-bit types

In general, it is:

1. When dealing with a large amount of data, use the smallest data type that can meet the requirements

Avoid type conversions. Try to keep the types consistent and use a single type in your calculations whenever possible.

3, if it is necessary to achieve better performance, tear down and start again, but to seriously deal with.

Three, you need to know how to access memory

1. Manipulating larger types of data is expensive because more instructions are used. Intuitively, the more instructions the worse the performance, the CPU has to do a lot of extra work

2. In addition, code and data reside in memory, and accessing memory has its own overhead. Because there is some overhead associated with accessing memory, the CPU caches the most recently accessed content, whether it is read or written to memory.

3. The CPU usually uses two-level cache or three-level cache:

  • Level 1 cache
  • The second level cache
  • Level 3 cache (usually used on server machine or game machine)

4. A cache miss occurs when data or instructions are not found in the cache. This is required to read data or instructions from memory. There are several cases of cache misses:

Note: The first cache miss is critical because the CPU waits until it reads an instruction from memory before continuing to execute.

Also: Modern cpus are capable of automatically prefetching memory in order to avoid or only limit cache misses.

Manage memory through garbage collection

1. A very important advantage of Java is garbage collection

  • How it works: Object memory that is no longer used is freed (reclaimed) by the garbage collector.
  • Note: Memory leaks can still occur.
  • The garbage collector manages your memory for you. It does more than just free unused memory.

2. Memory leak:

  • Memory is reclaimed only when an object is no longer referenced, and a memory leak occurs when the freed object reference still exists.
  • A typical example is when the entire Activity object leaks badly due to screen rotation! Because the Activity object takes up quite a bit of memory.

3. Avoid memory leak solutions. (Most are for analysis only and will not tell you if there is a memory leak)

  • The Heap and Tracker in the DDMS view track memory usage and allocation. The MONITOR in AS has four views: memory, network, and so on
  • The StrictMode class writes the results of detected violations to a log. It can only be used for analysis, and will not tell you if there is a memory leak
  • OneAPM has used, and also went to the interview, very good.

5. Better management through Java references

1. Memory free is an important feature of the garbage collector, playing a much larger role in the garbage collector than in memory management systems.

Java defines references to the types in 4

  • Strong:
    In the normal case of creating objects, keeping strong references to useless objects can lead to memory leaksCopy the code
  • Soft:
    Soft references and weak references are similar in nature. Soft references are suitable for caching and can automatically delete entries in the cacheCopy the code
  • Weak (Weak)
    Ensure that most of the next collection will be taken awayCopy the code
  • Virtual (shares)
    Very rarely usedCopy the code

3. You don’t have to implement a similar memory management system when it comes to caching or mapping. With carefully planned references, most of the work can be trusted to the garbage collector.

Garbage collection Garbage collection can trigger at any time, and you have little control over its timing. But sometimes, you can pass system.gc (); Note to Android, however, that the final time when garbage collection occurs is not determined by you.

Garbage collection occurs in the main thread of the application, so:

  • Likely to slow down response times and performance.
  • Frames are lost in timely games because too much time is spent in garbage collection.
  • For Android 2.3, the garbage collection has been moved to a separate thread. Much better than previous versions of Android

Six, through the system API can understand and manage memory

Android defines several apis that you can use to find out how much free memory the system has left and how much memory it is using

  • ActivityManager:

     getMomoryInfo()     
     getMomoryClass()     
     getLargeMeoryClass()Copy the code
  • The Debug of the

     dumpHprofData()
    getNativeHeapAllocatedSize()
    getNativeHeapSize()Copy the code

Tip: Set Android: largeHeap to true in your application’s manifest file to make your application use a larger heap.

Seven, when the memory can be handled this way

The ComponentCallbacks interface defines the API onLowMomory(), which is the same for all application group > components. When it is called, the component is basically asked to free memory that is not needed. Content that can be released:

  • Cache or cache entries (such as LruCache with strong references)
  • Bitmap objects that can be generated again on demand
  • Invisible layout objects
  • Database object

Eight, through the 5R method to optimize ANDROID memory:

1.Reckon(calculated)

First of all, you need to know the Memory consumption of your app, so that you can use the tools mentioned above to check the consumption. Here we recommend another Tool, Memory Analysis Tool (MAT) : it can be converted into pie charts and tables, intuitive and easy to use.

2.Reduce(decrease)

Reduce means to Reduce, and directly reducing memory usage is the most effective way to optimize.

Example: Bitmap:

Most OOM crashes are caused by manipulating bitmaps, which consume a lot of memory. Here are a few ways to handle images:

Pictures show:

For example, load thumbnails in a list for preview only.

Only when the user clicks on a specific item to see detailed information, then another fragment/activity/dialog box is launched to display the entire image

Image size:

InSampleSize is set with bitmapFactory.options to reduce system resource requirements.

BitmapFactory.Options bitmapFactoryOptions = new BitmapFactory.Options(); bitmapFactoryOptions.inJustDecodeBounds = true; bitmapFactoryOptions.inSampleSize = 2; // After setting inJustDecodeBounds to true, decodeFile does not allocate space, that is, BitmapFactory decoding the Bitmap is Null, but can calculate the length and width of the original image options. InJustDecodeBounds = false; Bitmap bmp = BitmapFactory.decodeFile(sourceBitmap, options);Copy the code

Image pixels:

There are four attributes for an image in Android: ALPHA_8:1byte memory for each pixel ARGB_4444:2 bytes memory for each pixel ARGB_8888:4 bytes memory for each pixel (default) RGB_565:2 bytes memory for each pixel

Android’s default color mode is ARGB_8888, which is the most delicate color mode and has the highest display quality. But again, it takes up the most memory. So use RGB_565 if the effect is not particularly high (565 has no transparency property) as follows:

public static BitmapreadBitMap(Contextcontext, intresId) { BitmapFactory.Optionsopt = newBitmapFactory.Options(); opt.inPreferredConfig = Bitmap.Config.RGB_565; opt.inPurgeable = true; opt.inInputShareable = true; InputStream is = context.getResources().openRawResource(resId); return BitmapFactory.decodeStream(is, null, opt); }Copy the code

Image recycling: After using Bitmap, you need to call bitmap.recycle () to release the memory space occupied by Bitmap without waiting for the Android system to release the memory space.

bitmap.recycle();  
  bitmap = null;Copy the code

Catch exception:

Bitmap bitmap = null; Try {// instantiate Bitmap Bitmap = bitmapFactory.decodefile (path); } catch (OutOfMemoryError e) {// Catch OutOfMemoryError, } if (bitmap == null) {return defaultBitmapMap if instantiation fails. }Copy the code

Modify reference:

If you just want to avoid OutOfMemory exceptions, you can use soft references. If you are more concerned about the performance of your application and want to reclaim some memory-consuming objects as quickly as possible, you can use weak references.

In addition, WeakHashMap is similar to weakreference. WeakHashMap For a given key, the existence of its mapping does not prevent the garbage collector from collecting the key, after which its entries are effectively removed from the map. WeakHashMap uses ReferenceQueue to implement this mechanism.

3.Reuse(re)

The core idea is to reuse existing memory resources and avoid creating new ones. The most typical uses are caches and pools.

4.Recycle(recycling)

Thread collection:

Thread t = new Thread() { public void run() { while (true) { try { Thread.sleep(1000); System.out.println("thread is running..." ); } catch (InterruptedException e) { } } } }; t.start(); t = null; System.gc();Copy the code

Cursor:

@Override protected void onDestroy() { if (mAdapter ! = null && mAdapter.getCurosr() ! = null) { mAdapter.getCursor().close(); } super.onDestroy(); }Copy the code

There are receivers, streams, and so on.

5.Review(check)

Code Review:

Code Review mainly checks some unreasonable parts in the Code or can be improved and optimized.

UI Review:

Android uses a lot of resources and memory to render the layout of controls in the view, so we need to pay attention to this part as well. Reduce the view hierarchy: Reducing the view hierarchy effectively reduces memory consumption because the view is a tree structure that is traversed every time it is refreshed and rendered.

Hierarchyviewer:

Hierarchyviewer Is a very useful tool that comes with the SDK in order to reduce view hierarchies.

You can find it at the following address: Your SDK path\ SDK \tools

Conclusion:

Deleting objects should be carefully considered because recreations are expensive.

Failing to free up enough memory can lead to more aggressive Android behavior (such as killing processes).

If the application process is killed, the user has to start all over again. Therefore, apps not only need to perform well, but also free up as many resources as possible. Deferred initialization is a good idea in code.

Memory on embedded devices is a scarce resource. While today’s phones and tablets have more and more memory, those devices are also running more and more complex systems and applications. Efficient use of memory not only allows applications to use less memory when running on older devices, but also allows applications to run faster. Keep in mind that your application’s memory requirements are endless.

Below the link, if you can not use timely message, inexplicably deleted link: pan.baidu.com/s/1hsK2Co0 password: ABCS