Android common memory leaks, learn these six strokes to optimize app performance

Source: Internet
Author: User

    1. Many developers know that the problem of memory leaks and memory overflows is often asked during an interview.

      1. Memory overflow (out of memory, or OOM), the popular understanding is that memory is not enough, that is, memory consumption exceeds the amount of memory space.

      2. Memory Leak, it is simple to understand that the memory is used after the garbage collection has not been recycled.

    2. 2

      Before you formally learn about memory leaks, start by briefly reviewing the Java memory allocation strategy.

      Java Program runtime memory allocation policy has three kinds, namely static allocation, stack allocation, heap allocation, the corresponding main memory space is static storage (also called method area), stack area, heap area.

      1. Static storage area (method area)

      It mainly stores static data, global static data, and constants. This block exists when the program is compiled, and it is present during the entire run of the program.

      2. Stack area

      When the method is executed, local variables in the method body are created on the stack and the memory held by these local variables is automatically freed at the end of the method execution. Because the stack memory allocation operation is built into the processor's instruction set, it is highly efficient, but the allocated memory capacity is limited.

      3. Heap Area

      Also known as dynamic memory allocation, usually refers to the memory that is directly new when the program is running. The Java garbage collector will be responsible for recycling this part if it is not in use.

    3. 3

      In Java, the allocation of memory is done by the program, and the release of memory is done by the GC, which greatly simplifies the work of the programmer, but at the same time aggravates the work of the JVM, which is one of the reasons why the Java program is running slower. In order to properly dispose of objects, the GC must monitor the running state of each object, including the object's application, reference, reference, assignment, etc., to monitor the object's state to release the object more accurately and in a timely manner, and the fundamental principle of releasing the object is that the object is no longer referenced.

      END
Memory leaks
    1. 1

      Java has garbage collection capabilities, programmers do not have to manually manage memory allocations, reduce the flash-back caused by segment errors, and reduce heap space bloat caused by memory leaks, making code more secure. However, there is still a possibility of memory leaks in Java, while Android uses Java as the development language, it is likely that a small error in the development process will cause memory leaks. When there is a memory leak, the app wastes a lot of memory, and it's often garbage collected due to insufficient memory, and you know that garbage collection is a time-consuming operation, which can lead to serious APP lag. At worst, the final program exits unexpectedly, even if the memory exhaustion results in outofmemery.

    2. 2

      Memory leaks are a headache for many developers, so let's take a look at Activity-related memory leaks today.

      In Android, the problem of leaking a context object is particularly serious, especially if a context object such as Activity references a lot of memory-intensive objects, and if the context object has a memory leak, all of the objects it references are leaked. Activity is a very heavyweight object, so we should try to avoid preventing it from being recycled, but the reality is that there are many ways to inadvertently disclose the activity object.

      END
Activity six strokes optimizing performance cheats
  1. 1

    1. Memory leaks due to static variables

    The simplest leak activity is to define a static variable in the activity class and point it to a running activity instance. If the reference is not cleared before the end of the Activity's life cycle, it will leak. Because the Activity's class object is static, once loaded, it will remain in memory while the APP is running, and if the class object is not unloaded, its static members will not be garbage collected.

  2. 2

    2. Memory leaks caused by singleton

    Another similar scenario is to implement a singleton pattern for frequently initiated Activity, so that its resident memory allows it to recover quickly.

    If we have a very time-consuming View created that stays the same Activity for a different life cycle, implement a singleton pattern for it. Once the View is loaded into the interface, it holds a strong reference to the Context, which is our Activity object.

    Since we referenced this View through a static member, we also quoted the activity, so the activity was compromised. So be sure not to assign the loaded View to a static variable, and if you really need to, ensure that it is removed from the view level before the Activity is destroyed.

  3. 3

    3. Memory leaks caused by internal classes

    We often define an inner class within the Activity, which can increase encapsulation and readability. But if we create an object of an inner class and hold a reference to the activity through a static variable, then there is also the possibility of an activity leak.

  4. 4

    4. Memory leaks caused by threads

    A memory leak can occur when an anonymous Asynctask object is defined within the Activity. If Asynctask is still executing after the activity is destroyed, it will prevent the garbage collector from reclaiming the activity object, causing a memory leak until the end of execution to reclaim activity.

    Similarly, the use of Thread and TimerTask can also lead to Activity leaks. As long as they are created through anonymous classes, they also hold strong references to Activity, which can lead to memory leaks, even though they are executed on separate threads.

  5. 5

    Memory leaks due to 5.Handler

    Defining an anonymous Runnable object and committing it to Handler can also lead to Activity leaks. The Runnable object indirectly references the activity object that defines it, and it is committed to the MessageQueue of handler, which causes the activity to leak if it is not processed when the activity is destroyed.

  6. 6

    6. Memory leaks due to resource not shutting down

    If system services can be obtained through context.getsystemservice, they are responsible for performing some background tasks or providing interfaces for hardware access. If the Context object wants to be notified when an event inside the service occurs, it needs to register itself in the listener for the service. However, this allows the service to hold a reference to the activity, and if the developer forgets to unregister when the activity is destroyed, the activity leaks.

    END
Summarize
    1. 1

      This is a simple analysis of the common memory leaks caused by Activity, in fact, there are many memory leaks, but the rationale is the same. Because of space reasons, here do not introduce too much, and then gradually analyze and learn.

      Although the memory of mobile phones is getting bigger and larger, memory leaks will not cause OOM as previously due to too little memory. However, excessive memory leaks can still cause memory overflow and affect the user experience, so it is important to solve the problem of memory leaks.

Android common memory leaks, learn these six strokes to optimize app performance

Related Article

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.