当前位置:网站首页>Oom out of memory memory overflow
Oom out of memory memory overflow
2022-06-28 18:42:00 【Novice Xiaowang】
When app Overhead memory exceeds allocation when memory , There will be a memory overflow
There are several reasons
The one-time memory cost is too large : Load macro, etc
Memory persistence overhead :listview Load picture scroll , Loop to create objects, etc
Memory recycling is not timely : Memory overhead is too high ,GC The frequency can not keep up with the overhead speed
Memory cannot be recycled : Memory leak leads to memory overflow, etc
Android Memory allocation and recycling mechanism
Android The system will only judge before the new memory allocation Heap Whether there is enough space left at the end of , If not enough, it will trigger GC operation , So as to free up more free memory space .
Android Of Heap Space is a GenerationalHeapMemory Model of , Recently assigned objects will be stored in YoungGeneration Area , When an object stays in this area for a certain time , It will be moved to OldGeneration, Finally, accumulate a certain time and move to PermanentGeneration Area .
The system will execute different data types according to different memory data types GC operation . for example , Just assigned to YoungGeneration Objects in the area are usually easier to destroy and recycle , At the same time YoungGeneration Regional gc Operating speed ratio OldGeneration Regional gc Faster . every last Generation All memory areas have a fixed size , As new objects are assigned to this area , When the total size of these objects reaches the threshold of this level of memory area , Will trigger GC operation , To make room for other new objects . Usually ,GC When it happened , All threads are suspended . perform GC The time it took and where it happened Generation It also matters , YoungGeneration Every time GC The operation time is the shortest , OldGeneration secondly , PermanentGeneration The longest . The length of execution is also different from the current Generation It depends on the number of objects in .
For the whole Android Memory control needs of the system ,Android The system sets a hard for each application DalvikHeapSize Maximum limit threshold , This threshold value will be changed on different devices because RAM It's different in size . If your application's memory footprint is close to this threshold , If you try to allocate memory again at this time , It's easy to cause OutOfMemoryError Error of .
// obtain Heap Size threshold
ActivityManager am =(ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
// The return value is in Mb In units of
int memoryClass = am.getMemoryClass();
as long as allocated + Newly allocated memory >= getMemoryClass() When it happens OOM.
avoid OOM Methods
1. Reduce the memory footprint of objects
avoid OOM The first step is to minimize the memory occupied by newly allocated objects , Try to use more lightweight objects .
Use lighter data structures
Use ArrayMap/ SparseArray replace HashMap And so on . ArrayMap yes Android The system is a container specially written for mobile operating system , in the majority of cases , Than HashMap More efficient , Less memory . SparseArray More efficient because they avoid key and value Of autobox Automatic boxing , And avoid unpacking after packing .
To avoid the Android It uses Enum
Android Official statement ”Enums often require more than twice as much memory as static constants. You should strictly avoid using enums on Android.“, Therefore, it should be avoided in Android Enumeration is used inside .
Reduce Bitmap Object's memory footprint
Bitmap Is a fat man who is very easy to consume memory , Reduce the of creation processing Bitmap Memory usage is very important , Usually there are the following 2 Measures :
inSampleSize: Zoom ratio , Before loading pictures into memory , We need to work out an appropriate scale first , Avoid unnecessary large image loading .
decode format: Decoding format , choice ARGB_8888/ RGB_565/ ARGB_4444/ ALPHA_8, There is a big difference .
Use smaller pictures
Corresponding resource picture , Pay special attention to whether there is compressible space in this picture , Can I use a smaller picture . Trying to use smaller pictures can not only reduce memory usage , It can also avoid a large number of InflationException. Suppose a big picture is XML The document refers directly to , It is very likely that when initializing the view, it will occur due to insufficient memory InflationException, The root cause of this problem is actually that OOM.
Reuse of memory objects
Reuse of most objects , The final implementation scheme is to use object pool technology , Or create an object pool in the program displayed when writing code , Then handle the reuse implementation logic , Or use some reuse features of the system framework to reduce the repeated creation of objects , So as to reduce the allocation and recycling of memory . stay Android The most commonly used caching algorithm above is LRU(Least Recently Use), The recommended operating principle is shown in the figure below :
Reuse the resources of the system
Android The system itself has many built-in resources , Such as a string 、 Color 、 picture 、 Animation 、 Style and simple layout, etc , These resources can be used directly in the application . This not only reduces the application's own load , Reduce APK Size . But be careful Android System version differences .
Pay attention to ListView/GridView Wait for a view with a large number of repeated sub components ConvertView Reuse of
Bitmap Reuse of objects
stay RecyclerView、ListView、GridView And other controls that display a large number of pictures LRU Mechanism to cache processed Bitmap. utilize inBitmap Advanced features of Android The system is in Bitmap Improve the efficiency of distribution and release execution . Use inBitmap Properties can tell Bitmap Decoder to try to use the existing memory area , New decoded bitmap Will try to use the previous one bitmap stay heap Occupied by pixel data Memory area , Instead of asking the memory to reapply an area to store bitmap. Take advantage of this feature , Even thousands of pictures , It will only take up the size of the number of pictures that can be displayed on the screen .
Use inBitmap Several restrictions that need attention :
stay SDK 11~18 Between , Reusable bitmap The size must be consistent , For example, to inBitmap The assigned image size is 100x100, So the new application bitmap Must also be 100x100 Can be reused . from SDK 19 Start , Newly applied bitmap The size must be less than or equal to the assigned bitmap size .
Newly applied bitmap With the old bitmap Must have the same decoding format , For example, the preceding bitmap yes 8888, I can't support it for so long 4444 and 565 Format bitmap 了 . We can create one that contains a variety of typical reusable bitmap Object pool , And so on bitmap You can find the right one ” Templates “ To reuse .
To avoid the onDraw Method to create objects
similar onDraw And other frequently called methods , You must pay attention to avoid creating objects here , Because it will rapidly increase the use of memory , And it's easy to cause frequent GC, Even memory jitter .
StringBuilder
When a large number of string splicing operations need to be used in the code , It is necessary to consider the use of StringBuilder To replace frequent ”+“.
Avoid memory leaks of objects
Memory object leak , Some objects that are no longer in use cannot be released in time , On the one hand, it takes up valuable memory space , It can easily lead to subsequent memory allocation , There is not enough free space OOM. obviously , It also makes every level Generation The free space of the memory area is reduced ,GC It's easier to trigger , Prone to memory jitter , This causes performance problems .
Be careful Activity Leakage of
Generally speaking ,Activity Memory leak is the most serious problem in memory leak , It takes up the most memory , Wide range of influence . Lead to Activity Two cases of leakage :
Internal class references cause Activity Leakage of
Activity Context Passed to other instances , This may cause itself to be referenced and leaked .
Consider using Application Context instead of Activity Context
For most non essential applications Activity Context The situation of (Dialog Of Context It has to be Activity Context), You can consider using Application Context instead of Activity Of Context, This can avoid inadvertent Activity leak .
Pay attention to temporary Bitmap Timely recycling of objects
A relatively large... Created temporarily bitmap object , After conversion, get a new one bitmap After object , The original should be recycled as soon as possible bitmap, This will release the original more quickly bitmap The space occupied .
Be careful Bitmap Class createBitmap() Method :
This function returns bitmap It's possible and source bitmap Is the same , When it comes to recycling , Special inspection is required source bitmap And return bitmap Is the quotation the same , Only in unequal circumstances , To be able to execute source bitmap Of recycle Method .
Pay attention to the cancellation of the listener
stay Android There are many needs in the program register and unregister The monitor for , Need to ensure timely delivery at the right time unregister Those listeners . Manual add Of listener, Need to remember in time remove This listener.
Note the object leak in the cache container
If the container is static or global , Then the objects stored inside should be timely remove.
Be careful WebView Leakage of
Android in WebView There are big compatibility issues , It needs to be destroyed at an appropriate time .
Be careful Cursor Whether the object is closed in time
For database queries Cursor, If it is not closed in time, it will cause leakage .
边栏推荐
- 19.2 容器分类、array、vector容器精解
- 记一次Emotet木马处理案例
- 被315点名的流氓下载器,又回来了…
- ONEFLOW source code parsing: automatic inference of operator signature
- 堆的概念和代码实现
- Chapter 2 processing files, cameras and GUI Cameo applications
- 软件测试的三个沟通技巧
- curl: (56) Recv failure: Connection reset by peer
- Cann media data processing V2, jpegd interface introduction
- 做跨境电商一定要学会用PRA软件,解放双手提高效率!
猜你喜欢

双功能交联剂丨Lumiprobe 磺基花青7二羧酸研究

解析机器人主持教学的实践发展

Database comparison tool

【C#】详解值类型和引用类型区别

【Unity3D】发射(RayCast)物理射线(Ray)

tensorboard 使用总结

Small program graduation project based on wechat subscription water supply mall small program graduation project opening report function reference

【软件测试】2022年普通高等学校招生全国统一考试

Mycat+分库分表

声网 VQA:将实时互动中未知的视频画质用户主观体验变可知
随机推荐
如何使用 SAP CDS view 中的 currency conversion 功能
实时Transformer:美团在单图像深度估计上的研究
Go, begin, end, for, after, instead of
基于固态激光雷达辅助的十六线机械雷达和单目相机的外参标定方法
打破学科之间壁垒的STEAM教育
konva系列教程3:自定义图形
东方财富软件股票开户是靠谱的吗?在哪开户安全
324. 摆动排序 II
使用.NetCore自带的后台作业,出入队简单模拟生产者消费者处理请求响应的数据
Small program graduation project based on wechat subscription water supply mall small program graduation project opening report function reference
Applet graduation project is based on wechat property maintenance application property applet graduation project opening report function reference
正版ST-link/V2 J-LINK JTAG/SWD引脚定义和注意事项
leetcode 1647. Minimum Deletions to Make Character Frequencies Unique(所有字母频率不同的最小删除次数)
声网 VQA:将实时互动中未知的视频画质用户主观体验变可知
AOSP清华镜像下载错误解决
Small program graduation project based on wechat milk tea takeout mall small program graduation project opening report function reference
Applet graduation project reservation based on wechat housekeeping service applet graduation project opening report function reference
安装nodejs环境
Concept and code implementation of heap
HackTheBox-baby CachedView