In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces the Android performance optimization memory optimization method related knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe everyone after reading this Android performance optimization memory optimization method article will have a harvest, let's take a look at it.
1. Android memory management mechanism 1.1 Java memory allocation model
Let's start with a picture of JVM dividing the memory into regions.
Program counter: stores the line on which the current thread executes the target method.
Stack memory: stack frames are stored in the Java stack, and each stack frame corresponds to a called method. Stack frame includes local scale
Operand stack.
Local method stack: the local method stack is mainly used to execute local methods. The Java stack serves to execute Java methods.
Method area: this area is shared by threads. It mainly stores the information of each class (class name, method information, field information, etc.), static variables, constants, and compiled code of the compiler.
Heap: the heap in Java is shared by threads, and there is only one heap memory in JVM, which mainly stores the object itself and the array
1.2 introduction to Dalvik and ART
Dalvik:Dalvik is a Java virtual machine designed by Google for Android platform. It can support the operation of Java applications that have been converted to .dex format, which is a compressed format specially designed for Dalvik applications and is suitable for systems with limited memory and processor speed. Dalvik is optimized to allow multiple virtual machine instances to run simultaneously in limited memory, and each Dalvik application executes as a separate Linux process. Separate processes can prevent all programs from being shut down when the virtual machine crashes.
ART:ART said that Android Runtime,Dalvik relies on a just-In-Time compiler to interpret bytecode, and run-time compiled applications need to run on users' devices through an interpreter, which is not particularly efficient, but makes it easier for applications to run on different hardware and architectures. ART has completely changed this practice by precompiling the bytecode to the machine language when installing the application, a mechanism called precompilation. In the process of removing the interpreted code, the application executes more efficiently and starts faster.
Advantages of ART:
1. Higher system performanc
two。 The startup speed of the application is faster, the experience is better, and the tactile feedback is more timely.
3. Longer battery life
4. Support for lower hardware
Disadvantages of ART:
1. It takes up more storage space.
two。 Applications take longer to install.
The difference between Dalvik and ART
1.Dalvik compiles and runs every time, and art only starts compilation when it is installed.
2.art takes up more space than Dalvik, which means exchanging space for time.
3.art reduces compilation, reduces CPU usage frequency, and significantly improves battery life.
4.art starts, runs faster, experiences better, and tactile feedback is more timely.
1.3 Why should memory be optimized
1. Reduce oom and improve application stability
two。 Reduce stutter and experience better
3. Reduced memory footprint and higher application survival rate
4. Deal with some abnormal hidden dangers ahead of time.
2. Java memory recovery algorithm 2.1 an algorithm to determine whether an object in Java is alive or not
2.1.1 reference counting algorithm
Each object in heap memory has a reference counter, when the object is referenced, the counter + 1, when the reference expires, the counter-1, when the value of the counter is 0, indicating that the object is not referenced, it will be considered a garbage object, and the system will reclaim the memory and reallocate it.
Advantages: the execution of the reference counter is simple and the judgment efficiency is high.
Disadvantages: it is difficult to determine the circular reference object, and the reference counter increases the overhead of program execution, which is no longer used after jdk1.1.
2.1.1 Root search method
GC Roots object as the starting point, and then search down, the search path is called reference chain, when an object is not connected to GC Roots with any reference chain, the object is unreachable, that is to say, the object is garbage and can be recycled.
In Java, there are four kinds of objects that can be used as GC Roots:
1. Objects referenced in the virtual machine stack
two。 Objects referenced by static properties of a class in the method area
3. Objects referenced by constants in the method area
4. Reference object of JNI in the local method stack
2.2 JVM garbage collection algorithm
2.2.1 Marker removal
In the most basic garbage collection algorithm, the algorithm is divided into two stages: marking and clearing: first, all the objects that need to be recycled are marked, and all the marked objects are recycled after the marking is completed.
Disadvantages: inefficient, followed by a large number of discontiguous memory fragments, causing another garbage collection action to be triggered in advance.
2.2.2 replication recovery algorithm
The copy recovery algorithm divides the available memory into two equal blocks according to its capacity, and uses only one of them at a time. When this memory is used up, the surviving objects are copied to another piece of memory, and then the used memory space is cleared at one time, so that one of the pieces of memory is reclaimed each time, and complex situations such as memory fragments are not taken into account in memory allocation.
Cons: the usable memory is reduced to half of the original.
2.2.3 marking finishing method
The tag-sorting algorithm is improved on the basis of the mark-removal algorithm. The recyclable objects are marked in the marking stage. After the marking is completed, the recyclable objects are not cleaned directly, but all the surviving objects are moved to one end. In the process of moving, clean up the recyclable objects.
Advantages: compared with tag cleanup, tag defragmentation does not cause a large number of discontinuous memory fragmentation problems.
Disadvantages: if more replication operations are performed in the case of high object survival rate, the efficiency will be greatly reduced, while in the case of low survival rate, the efficiency will be greatly improved.
2.2.4 Generation collection and recovery algorithm
At present, commercial virtual machines use generation-by-generation collection algorithm, which divides the memory into several blocks according to the different periods of object survival, and generally divides the java heap into the younger generation, the old generation and the permanent generation. Then according to the characteristics of each era to adopt different collection algorithms, the survival rate of the younger generation is lower, the replication recovery algorithm is adopted, the survival rate of the old object is higher, and the label removal method or tag finishing method is used for recovery.
3. Memory problem manifestation 3.1 memory jitter
The memory wave graph is jagged, and gc frequently causes stutters.
3.2 memory leak
Memory leak simply means that the memory allocated by the system cannot be released for some reason, and the memory will become smaller and smaller, eventually leading to oom.
3.3 memory overflow
That is, OOM,OOM will cause a program exception. After the Android device is shipped from the factory, the maximum memory allocation of the java virtual machine to a single application is determined, and if this value is exceeded, it will OOM.
4. Memory optimization tools 4.1 Memory Profiler
Memory Profiler is a tool that comes with Android studio. It shows the memory usage of applications in the form of real-time charts. It can be used to identify memory leaks, jitters, etc.
Note: if Profiler is not found in the console, open it with View-> Tool Windows-> Profiler.
Advantages: convenient and intuitive, easy to use offline
4.2 Memory Analyzer (MAT)
1. Powerful java heap analysis tool to find memory leaks and memory footprint
2. Generate an overall report to facilitate the analysis of the problem
3. It can be used offline.
MAT uses:
Get the hprof file
The exported Dump cannot be opened directly using mat. Android SDK comes with a conversion tool under SDK's platform-tools, where the conversion statement is:
Cd D:\ aa\ sdk\ platform-tools
Hprof-conv aaa.hprof bbb.hprof
Note: aaa.hprof represents the dump file exported from profiler, and bbb.hprof represents the converted dump file.
Use mat to open the converted dump
MAT view
On the MAT window, OverView is an overview that shows the overall memory consumption and suspected problems.
1. Histogram: list all instance objects in memory, number and size, and support regular expression lookup in the top regex area
2. Dominator Tree: list the largest objects and their dependent surviving Object. Compared with Histogram, it is more convenient to see the reference relationship.
3. Top Consumers: list the largest Object by image
4. Leak Suspects: an overall report that automatically analyzes the causes and leaks of memory leaks through MAT
When analyzing memory, we basically use Histogram and Dominator Tree.
Class Name: class name.
Objects: the number of object instances.
Shallow Heap: the amount of memory occupied by the object itself, excluding the objects it references
Retained Heap: is the sum of the current object size and the size of the object referenced directly or indirectly, including recursively released.
Find the mode of memory leak
Step 1: match by package name in Regex. Of course, you can also match in other ways.
Step 2: right-click to select the suspect, List objects-- > with incoming references
Note with outgoing references, he quoted those objects.
With incoming references, those objects quoted him.
Step 3: select the current exclude All weak soft virtual reference of Path to GC Roots/Merge to GC Roots.
When this appears in the lower-left corner of the icon, it indicates a memory leak. Then call back for analysis in the code.
4.3 LeakCanary
Use
Implementation 'com.squareup.leakcanary:leakcanary-android:1.5.4'
In application
Public class App extends Application {private RefWatcher mRefWatcher; @ Override public void onCreate () {super.onCreate (); mRefWatcher = LeakCanary.install (this);} public static RefWatcher getRefWatcher (Context context) {App application = (App) context.getApplicationContext (); return application.mRefWatcher;}}
The call to the onDestory () method in activity or fragment
RefWatcher refWatcher = App.getRefWatcher (getActivity ()); refWatcher.watch (this)
Principle
WeakReference + ReferenceQueue is mainly used to determine whether the object is reclaimed by the system GC. When the WeakReference is created, a ReferenceQueue object is passed. When the life cycle of the object referenced by the WeakReference ends, it will be added to the ReferenceQueue. After the GC, the object has not been added to the ReferenceQueue, and there may be a memory leak. GC will be triggered again and the second confirmation will be made.
5. Common memory leaks 1. Resource objects are not closed
When a resource object is no longer in use, you should immediately call its close () function, turn it off, and then set it to null. For example, resources such as Bitmap are not closed, which will cause memory leaks. At this time, we should close them in time when Activity is destroyed.
2. The registered object is not logged out.
For example, for memory leaks caused by the failure to log out of BraodcastReceiver and EventBus, we should log out in time when Activity is destroyed.
3. The static variable of the class holds the big data object
Try to avoid using static variables to store data, especially big data objects, and it is recommended to use database storage.
4. Memory leakage caused by a single case
Give priority to the Context of Application. If you need to use the Context of Activity, you can encapsulate the Context with a weak reference, and then get the Context from the weak reference where it is used. If you cannot get it, you can simply return it.
5. Static instance of non-static inner class
The life cycle of the instance is as long as that of the application, which causes the static instance to hold the reference to the Activity all the time, and the memory resources of the Activity cannot be reclaimed normally. At this point, we can set the inner class as a static inner class or extract it and encapsulate it into a singleton. If you need to use Context, try to use Application Context. If you need to use Activity Context, remember to leave it empty so that GC can be recycled, otherwise it will still leak memory.
6. Handler temporary memory leak
After the Message is issued, it is stored in the MessageQueue. There is a target in the Message, which is a reference to the Handler. If the Message exists in the Queue for too long, the Handler cannot be recycled. If the Handler is non-static, it will cause Activity or Service to not be recycled. And the message queue constantly polls messages for processing in a Looper thread. When the Activity exits, there are still unprocessed messages or messages being processed in the message queue, and the Message in the message queue holds the reference of the Handler instance, and the Handler holds the reference of the Activity, so the memory resources of the Activity can not be reclaimed in time, causing a memory leak. The solution is as follows:
1. Use a static Handler inner class, and then use weak references to objects held by Handler (usually Activity), so that objects held by Handler can also be recycled when recycling.
2. In the Destroy or Stop of Activity, the messages in the message queue should be removed to avoid the messages to be processed in the message queue of the Looper thread. It should be noted that AsyncTask is also an internal Handler mechanism, and there is also a risk of memory leaks, but it is generally temporary. For memory leaks like AsyncTask or threads, we can also separate the AsyncTask and Runnable classes or use static inner classes.
7. Memory leakage caused by non-cleaning of objects in the container
Before exiting the program, clear the things in the collection, then set it to null, and then exit the program
8 、 WebView
WebView has the problem of memory leak, as long as WebView is used once in the application, the memory will not be released. We can start a separate process for WebView and use AIDL to communicate with the main process of the application. The process of WebView can be terminated at an appropriate time according to the needs of the business to achieve the purpose of releasing memory normally.
9. Memory leaks caused by using ListView
When constructing an Adapter, the cached convertView is used.
6. Ways to optimize memory space 6.1. References to java objects
Strong references: basically 99% of the code we develop and write are strong references.
Soft reference: if an object has a soft reference, it will be reclaimed when there is insufficient memory.
Weak reference: when GC, whenever a weak reference is found, it will be recycled. Of course, it is possible that there is a GC many times before it is found.
Virtual references: virtual references must be associated with reference queues. It can be recycled by the garbage collector at any time. Generally, it can be used to judge the frequency of GC. If the GC frequency is too high, then there is something wrong with the memory. At the same time, you can monitor whether an important object has been recycled.
Therefore, in peacetime when we write code, the appropriate use of soft references, weak references, can also play an important role in our memory optimization.
6.2. Reduce unnecessary memory overhead
1 、 AutoBoxing
The core of autoboxing is to convert the underlying data type to the corresponding wrapper class. For example, the int type only takes 4 bytes, but the Integer object takes 16 bytes.
2. Memory reuse
Resource reuse: general string, color definition, reuse of simple page layout
View reuse:
3. Use optimized data types
Such as SparseArray, SparseBooleanArray, LongSparseArray, using these API can make our program more efficient. The HashMap utility class is relatively inefficient because it needs to provide an object entry for each key-value pair, while SparseArray avoids the time it takes to convert basic data types to object data types.
4. Use less enumerations in projects
Enumerations take up three times as much memory as constants.
5. Actively release memory when the memory of the application is too low.
In onTrimMemory/onLowMemory in application, this method is called back when memory is tight. In this method, we can release the image cache and static cache to avoid being kill.
6. Avoid creating unnecessary objects
For example, when concatenating strings, do not use "+" to concatenate, but use StringBuffer,StringBuilder instead. Because the interior of String is decorated by final and cannot be inherited, splicing with + results in a new object that takes up memory.
7. Try not to create objects in some looping places.
For example, when customizing, use the onDraw () method.
7. Elegant inspection big picture
Projects will often encounter such a situation, our layout, the width and height of the control may only be 50 * 50, but the image from the server or UI to the picture will often be much larger, and if the picture in the resource file is good, you can directly view the width and height, but if you get from the server, this is often ignored. If the picture is too large, it will take up more memory, which is not necessary. So how do we detect that the image given by the server is too large?
7.1.inherit ImageView and re-implement onDraw ()
In this way, we can re-measure the width and height of the picture, beyond a certain range, we can output a warning. But this method is very intrusive to the code. If new students join, it is easy to cause code confusion.
7.2 、 ARTHook
Hook means hooks, that is, messages can be hooked to prevent them from being passed, and we can perform our own operations for different messages or api before they are executed.
The Epic framework is recommended here: https://github.com/tiann/epic
Add dependency
Implementation 'me.weishu:epic:0.3.6'
Create an ImageHook class
Package com.optimize.performance.memory;import android.graphics.Bitmap;import android.graphics.drawable.BitmapDrawable;import android.graphics.drawable.Drawable;import android.util.Log;import android.view.View;import android.view.ViewTreeObserver;import android.widget.ImageView;import com.optimize.performance.utils.LogUtils;import com.taobao.android.dexposed.XC_MethodHook;public class ImageHook extends XC_MethodHook {@ Override protected void afterHookedMethod (MethodHookParam param) throws Throwable {super.afterHookedMethod (param) / / implement our logic ImageView imageView = (ImageView) param.thisObject; checkBitmap (imageView, (ImageView) param.thisObject) .getDrawable ();} private static void checkBitmap (Object thiz, Drawable drawable) {if (drawable instanceof BitmapDrawable & & thiz instanceof View) {final Bitmap bitmap = ((BitmapDrawable) drawable) .getBitmap () If (bitmap! = null) {final View view = (View) thiz; int width = view.getWidth (); int height = view.getHeight () If the width and height of the if (width > 0 & & height > 0) {/ / icon is more than twice that of the view band, warn if (bitmap.getWidth () > = (width = (height 0 & & h > 0) {if (bitmap.getWidth ()) > (w = (h)).
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.