Android app solves slow memory jitter and memory leaks (discovery and positioning)

Source: Internet
Author: User

Memory jitter is a phenomenon in which a large number of objects are created or recycled in a short period of time, and the cause of memory jitter is mostly frequent (important) to create objects in the loop (resulting in a large number of objects being created in a short time, because new objects are to occupy memory space and are frequent, If one or two times in the loop to create objects in the memory has little impact, does not cause serious memory jitter is acceptable and inevitable, frequent memory jitter is very serious), the impact of memory jitter is if jitter is very frequent, will cause the garbage collection mechanism to run frequently (a large number of objects in a short period of time, the need for large amounts of memory, And with frequent jitter, it may be necessary to reclaim memory for object generation, and the garbage collection mechanism will naturally run frequently. In a comprehensive way, frequent memory jitter can cause garbage collection to run frequently.

Memory leak refers to the existence of a program in a certain part of the function is not necessary, but the garbage collection mechanism to recover memory when the memory is still needed to detect, can not be recycled, this program in the unused but can not be recycled memory is leaked memory, then why this? Normal words should be the program does not need the memory can be recycled, this is the garbage collection mechanism to do, if the garbage collection mechanism is normal operation, should not be so ah, but the actual garbage collection mechanism is normally the case of a memory leak. In fact, the Java programmer has to know the garbage collection mechanism, determine whether a piece of memory is garbage, the condition is recoverable, this condition is to check if there is a reference and referenced relationship, the relationship is not present, it is considered recyclable, if there is a reference or referenced relationship, it is considered not recyclable, It is now possible to know that the cause of the memory leak is that the programmer has not removed the unused memory from the reference relationship (because most of the memory oil objects in the program are pointing, so removing the reference relationship is empty). Memory leaks can cause some memory not to be used properly, in other words, it is possible to use less memory, so light increases the garbage collection mechanism running frequency, heavy memory overflow (when the system needs to allocate a piece of memory, but the existing memory in the garbage collection running after the run is insufficient, memory overflow); To avoid a memory leak, When you write a program, you have determined that you do not need a reference variable, you can empty it, even if the memory is not disclosed, there may be memory overflow, then the memory overflow is a different problem caused.

1) Memory churn and performance (RAM Jitter and performance)

Although Android has a mechanism for automating memory management, improper use of memory can still cause serious performance problems. Creating too many objects in the same frame is something that needs special attention.

The Android system has a generational Heap memory model that performs different GC operations based on the different memory data types in memory. For example, recently allocated objects are placed in the young generation area, where objects are usually quickly created and destroyed quickly, while the GC operation speed of this area is also faster than the GC operation of the old generation region.

In addition to the speed difference, when performing GC operations, any action on any thread will need to be paused, waiting for the GC operation to complete before other operations can continue to run (so the fewer times the garbage collection runs, the less impact on performance).

In general, a single GC does not take up too much time, but a large number of non-stop GC operations can significantly occupy the frame interval (16ms). If there are too many GC operations in the frame interval, then natural other similar calculations, rendering operations such as the availability of time has become less.

There are two reasons why a GC can be performed frequently:

· Memory jitter is churn, and memory jitter is caused by a large number of objects being created and released in a short period of time.

• Generating a large number of objects in an instant can seriously occupy the memory area of young generation and will trigger the GC when the threshold is reached and the remaining space is insufficient. Even though each allocated object consumes little memory, stacking them together increases the pressure on the heap, triggering more other types of GC. This operation may affect the frame rate and make the user aware of the performance problem (frame rate is the concept of Android rendering mechanism, leading to slow lag of the direct cause, is the rendering mechanism is blocked, about the rendering mechanism has another blog specifically said, want to know can click here).

There is a simple and intuitive way to solve the above problem, and if you look inside memory monitor to see how many times the ram has occurred in a short time, this means that memory jitter is likely to occur.

We can also use allocation tracker to see the same objects that are constantly in and out of the same stack within a short period of time. This is one of the typical signals of memory jitter.

After you have roughly positioned the problem, the next fix is relatively straightforward. For example, you need to avoid allocating objects to memory in a for loop, and you need to try to move the creation of objects outside the loop body, and the OnDraw method in the custom view needs to be noticed, and the OnDraw method is called every time the screen is drawn and the animation is executed. Avoid complex operations within the OnDraw method and avoid creating objects. For those who cannot avoid the need to create objects, we can consider the object pool model, through the object pool to solve the problem of frequent creation and destruction, but it is important to note that after the end of use, you need to manually release objects in the object pool.

2) Garbage Collection in Android (Android garbage collection)

The recycling mechanism of the JVM is a great benefit to developers, and instead of dealing with the allocation and recycling of objects at all times, you can focus more on more advanced code implementations. Compared with languages such as java,c and C + +, they require developers to focus on the allocation and recycling of objects, but in a large system, it is unavoidable that some objects forget to recycle, this is the memory leak.

The GC mechanism in the original JVM has been largely optimized in Android. Android is a three-level Generation memory model, the most recently allocated objects will be stored in the young Generation area, when the object stays in this area for a certain amount of time, it will be moved to the old Generation, Finally to the permanent generation area.

Each level of memory area has a fixed size, and since then constantly new objects are assigned to this area, when the total size of these objects quickly reached the threshold of this level of memory area, will trigger the GC operation, in order to make room for other new objects.

As mentioned earlier, every time a GC occurs, all of the threads are in a paused state. The time taken by GC is also related to which generation it is, and young generation each GC operation time is shortest, old generation second, Permanent generation the longest. The length of execution is also related to the number of objects in the current generation, and traversing a lookup of 20,000 objects is much slower than traversing 50 objects.

While Google's engineers are trying to shorten the time it takes for each GC, it's important to pay particular attention to GC-led performance issues. If you accidentally perform an action to create an object inside the smallest for loop unit, this can easily cause a GC and cause performance problems. With memory monitor, we can see how much ram is being consumed, and every instant the memory loss is due to a GC operation, and if a lot of memory goes up and down in a short period of time (Memory heavy jitter), it is possible that there is a performance problem here. We can also use the heap and Allocation tracker tool to see what objects are allocated in memory at this time.

Here is a brief introduction to memory Jitter (concept and judgment method, which is used by two tools, one for determining whether there is a severe memory jitter in the memories Monitor, one for confirming the jitter location heap and Allocation Tracker), And a more detailed description of the garbage collection mechanism in Android.

2) performance cost of memory Leaks (RAM leak)

Although Java has a mechanism for automatic recycling, this does not mean there is no memory leak in Java, and memory leaks can easily lead to serious performance problems.

Memory leaks mean that objects that are no longer used by the program cannot be recognized by the GC, which causes the object to remain in memory and consume valuable memory space. Obviously, this also makes the memory area of each level of generation less space available, and GC is more susceptible to triggering, which can cause performance problems.

Finding a memory leak and fixing the vulnerability is tricky, and you need to be familiar with the code you're executing, knowing exactly how it works in a particular environment, and then carefully troubleshooting it. For example, do you want to know if an activity in the program exits with a complete release of the memory it used before? First you need to use the heap tool to get a memory snapshot of the current state while the activity is in the foreground, and then you need to create a blank activity that takes up almost no memory to jump to the previous activity. Next, when jumping to the blank activity, call the System.GC () method to ensure that a GC operation is triggered. Finally, if the memory of the previous activity is all properly freed, there should be no object in the previous activity in the memory snapshot after the blank activity is started.


About memory jitter and memory leaks here, let's talk about the memory optimization tools that Android Studio provides

Android Studio provides tools to help developers discover and resolve memory jitter and memory leaks.

Tool-memory Monitor (used to detect memory jitter and memory leaks)

Memory Monitor in Android Studio is a great help for us to see how our programs are being used.


The following content is important, the following is important, important things to say three times

· Memory Monitor: To see the entire app footprint and the timing of GC, a large number of GC operations over a short period of time is a dangerous signal (used to detect memory leaks and severe memory jitter).

The next two are the exact locations where memory jitter and memory leaks occur for positioning ·

Allocation Tracker: Use this tool to track the allocation of memory, as mentioned earlier.

Heap Tool: View the current memory snapshot to facilitate a comparative analysis of which objects may be leaking.

You can now navigate to a piece of code that has a memory leak or jitter.

If it is a memory leak resolution, it is straightforward to empty the leaking object at the appropriate time.

But if only the memory jitter, scored two cases, because the memory jitter is created in a short period of time to create a large number of objects caused (usually in the loop to create objects), the direct way is not to create a large number of objects in a short time, if the process of creating objects can get out of the loop without affecting functionality, this situation is easier to solve But more is another situation, is unable to get the loop outside, otherwise affect the function. In the second case, the object should be created in the loop, but the number of objects must be controlled. This is still the next article in the description of the solution.

.

Android app solves slow memory jitter and memory leaks (discovery and positioning)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.