当前位置:网站首页>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 .
边栏推荐
- leetcode 1423. Maximum Points You Can Obtain from Cards(从牌中能得到的最大点数和)
- Chapter 2 processing files, cameras and GUI Cameo applications
- 注意!PMP紧急缓考今天就截止了!
- 深入解析kubernetes中的选举机制
- render函数解析
- 正版ST-link/V2 J-LINK JTAG/SWD引脚定义和注意事项
- select/poll/epoll
- Analysis of response parsing process of SAP ui5 batch request
- id门禁卡复制到手机_怎么把手机变成门禁卡 手机NFC复制门禁卡图文教程
- tensorboard 使用总结
猜你喜欢

记一次Emotet木马处理案例

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

Learning notes: how to time 10ms for 51 single chip microcomputer (STC89C52)

Small program graduation design based on wechat driving school examination small program graduation design opening report function reference

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

数据库对比工具

180.1.连续登录N天(数据库)

Easyexcel learning notes

Yixin Huachen: real estate enterprises want to grasp the opportunity of the times for digital transformation

Small program graduation project based on wechat subscription water supply mall small program graduation project opening report function reference
随机推荐
Small program graduation project based on wechat chess and card room small program graduation project opening report function reference
匿名函数this指向以及变量提升
Database comparison tool
Upload file list (repeated file names are marked with brackets)
io模型初探
从理论到实践增强STEAM和工程教育
Small program graduation project based on wechat subscription water supply mall small program graduation project opening report function reference
Unity about oculus quest2 basic development based on XR interaction toolkit 003- capture function - making a VR bowling game
基于固态激光雷达辅助的十六线机械雷达和单目相机的外参标定方法
Graphic system - 1 Layout loading
Object tracking using tracker in opencv
Concept and code implementation of heap
EasyExcel 学习笔记
use. NETCORE's own background job, which simply simulates producers and consumers' processing of request response data in and out of the queue
FFmpeg学习总结
Konva series tutorial 3: Customizing drawings
软件测试的三个沟通技巧
数据库对比工具
如何设计业务高性能高可用计算架构 - 作业
安装nodejs环境