Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Android memory Optimization Strategy

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces the example analysis of Android memory optimization strategy, which has a certain reference value, and interested friends can refer to it. I hope you will gain a lot after reading this article.

I. memory optimization strategy

Memory optimization generally starts from two directions: on the one hand, it is written in the previous blog to prevent memory leakage and avoid unnecessary waste of memory resources; on the other hand, it is the optimization of large objects in APP to reduce the memory occupied by large objects.

Second, the specific optimization point 1. Avoid memory leaks

Just read the previous blog here:

Detailed explanation of Android memory leak and optimization scheme

Optimization strategy for large objects such as 2.Bitmap

Image loading is the main culprit of memory consumption, and it is also the most common, so it is critical to optimize the memory footprint of bitmap.

The memory calculation formula for Bitmap is as follows:

Memory occupied by Bitmap = resolution * memory of a single pixel

For example, a 1920 * 1080 image takes up 1920 * 1080 * single pixel memory. Therefore, the optimization of Bitmap can be optimized from two aspects: resolution and single pixel.

(1) optimize Bitmap resolution

Usually, when an APP loads an image, the size of the ImageView is determined. For example, if the size of an ImageView is set to 100x100, but the resolution of the loaded Bitmap is 200x200, then the resolution of the 'Bitmap' can be compressed to' 100x100' by sampling compression. Through this compression operation, the memory size can be directly reduced by 4 times. The code is as follows:

Val options = BitmapFactory.Options () options.inSampleSize = 2 / / if the sampling rate is set to 2, one pixel will be taken for every two pixels, and the final resolution width will be changed to the original 1/2val bitmap = BitmapFactory.decodeResource (resources, R.drawable.image, options) (2) optimize the memory of a single pixel.

The image in the computer is generally composed of red, green and blue channels plus a transparent channel, so a pixel is also composed of red, green, blue, and a transparent channel, corresponding to the memory is represented by byte, for example, using 2 byte to store a pixel, then each channel takes up 4 bit of memory, while if 4 byte is used to store a pixel Then each channel takes up 1 byte. 4-byte pixels can represent more colors than 2-byte pixels, so the image quality of four-byte pixels is clearer. (an Byte consists of 8 bits and is the basic unit of data storage. 1Byte is also known as a byte.)

The memory occupied by a single pixel in the Bitmap of Android is related to the inPreferredConfig parameter configuration of Bitmap. The code is set as follows:

Final BitmapFactory.Options options = new BitmapFactory.Options (); options.inJustDecodeBounds = true;// only parses the edge of the image to get the width and height options.inPreferredConfig = Bitmap.Config.RGB_565; BitmapFactory.decodeFile (filePath, options); / / calculate the zoom ratio options.inSampleSize = calculateInSampleSize (options, desWidth, desHeight); / / return bitmap options.inJustDecodeBounds = false for fully parsing the image Bitmap bm = BitmapFactory.decodeFile (filePath, options)

The parameters set by options.inPreferredConfig = Bitmap.Config.RGB_565; are as follows:

Config setting occupies memory (byte) Note ALPH_81 contains only one transparent channel, transparent channel occupies 8bit, that is, 1byteRGB_5652 contains R/G/B three color channels, does not contain transparent channels, the memory occupied by the three channels is 5bit/6bit/5bitARGB_44442 has been discarded, including A/R/G/B four color channels, each channel occupies 4bitARGB_8888424 bit true color, Android default configuration 8bitRGBA_F168Android 8.0 per channel, 16bit per channel, that is, two bytes

In the Android system, the default color mode of Bitmap is ARGB_8888, that is, each pixel occupies 4byte. By default, a picture with a resolution of 1920 * 1080 takes up 1920 * 1080 * 4 = 7.91m of memory when loaded into memory.

You can set the corresponding color mode by setting the inPreferredConfig parameter. For example, for a picture that does not contain a transparent channel, we can set it to RGB_565, which ensures the quality of the picture and reduces the footprint.

At this point, the memory size of a 1920 * 1080 image loaded into memory is 1920 * 1080 * 2 = 3.955m, which is half of the memory footprint by default.

(3) caching strategy of Bitmap

The problem of memory footprint can also be optimized to some extent through the cache strategy. For example, the three-level local cache strategy is adopted in the Glide framework to achieve Bitmap optimization, by setting active cache, LRU memory cache and local cache. For ImageView with the same parameters, keep only one copy in memory to reduce the memory size.

(4) choose a suitable drawable folder for drawable resources.

For example, if we only put a 100x100 image in the hdpi directory, according to the conversion relationship, the resolution matching to the xxhdpi phone will be stretched to 200cm 200 when referencing the image. It should be noted that in this case, the memory footprint will increase significantly. For images that do not want to be stretched, you need to put them in the assets or nodpi directory.

(5) Optimization of other large objects.

More lightweight data structures can be used. For example, we can consider using traditional data structures such as ArrayMap/SparseArray instead of HashMap, and HashMap displays are inefficient and take up more memory in most cases than ArrayMap containers written by Android systems specifically for mobile operating systems. In addition, SparseArray is more efficient because it avoids the automatic packing of key and value, and avoids unpacking after packing.

(6) avoid memory jitter

Memory jitter refers to the sudden creation of a large number of objects in a short period of time, frequently causing GC recycling, resulting in memory fluctuations. Frequent object creation should be avoided in development to avoid memory jitter. Because memory jitter will trigger GC frequently, and GC will cause STW problems, which will directly affect the performance of the program.

For example, when drawing custom View, be sure to avoid creating objects in onDraw or onMeasure.

3. Native API callback frees memory

The Android system provides some callbacks to notify the memory usage of the current application, such as the following two methods:

OnLowMemory () generally speaking, when all Background applications are dropped by kill, forground applications will receive a callback from onLowMemory (). In this case, it is necessary to release the non-essential memory resources of the current application as soon as possible to ensure that the system can continue to run stably. In particular, to release the cached Bitmap resources in Glide, recycle the resources by calling the Glide.onLowMemory method.

The onTrimMemory () Android system has also provided a callback of onTrimMemory () since 4.00.When the system memory reaches certain conditions, all running applications will receive this callback. At the same time, the following parameters will be passed in this callback, representing different memory usage. When receiving the onTrimMemory () callback, you need to judge according to the passed parameter type and reasonably choose to release some of your own memory footprint. On the one hand, it can improve the overall running fluency of the system, and on the other hand, it can avoid the applications that need to be killed first by the system. For example, call Glide.onTrimMemory () to recycle bitmap.

4. Memory troubleshooting tool (1) LeakCanary monitors memory leaks

In debug mode, LeakCanary is always on to detect memory leaks, and the location of memory leaks can be quickly located according to the references provided by LeanCannary.

(2) Monitoring memory through Proflier

After the development of a function, you can use Profiler to detect the memory usage of APP. Repeatedly open and close the page, and then trigger GC, whether the memory can be reduced.

(3) troubleshoot memory leaks through MAT tool

MAT provides powerful capabilities to view objects' deep heap, shallow heap memory size, and so on.

Thank you for reading this article carefully. I hope the article "sample Analysis of Android memory Optimization Strategy" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report