EditText in Android Leaks memory - experiment yourself.

A memory leak is the state of a class where some objects of the class are not utilized by the app at some point in time, and the Garbage Collector thinks that they are a part of the app. It’s because you still hold a reference to the context that prevents the Garbage Collector from understanding it. OutOfMemoryError is usually triggered by memory leaks. ANR also happens because of such memory leak issues.

Keeping the garbage (unused objects) is not really good practice. We should let the Garbage Collector clean out the stuff. You need to free all the references to the object once their usage is complete. This is the right way to do memory leak free programming. If the objects are kept referenced for the end of the lifecycle, it always leads to memory leaks. Any rouge references can hold an object in memory permanently and can cause the garbage collector to not act on them. In case of such allocations pileup, it will lead to abnormal memory usage and ultimately to OutOfMemoryExceptions.

Though the above-mentioned practice helps you build an efficient application there are scenarios where there is nothing you can do to stop a leak. One such scenario is where the EditText in Android leaks memory, EditText in an Activity is holding a strong reference to an Activity even once it is finished.

The leak can be observed by profiling the app while running the project in any physical device.

Shown below is the memory profile graph of an app without an EditText.

notleaking.gif

Now, Add Edit Text code in your activity xml

    android:id="@+id/leakyEditText"
    android:layout_below="@id/nonLeakyTextView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Memory leaking..."/>

A continuous rise in memory allocations can be observed as soon as EditText field is in focus, which unfortunately cannot be stopped.

leaking.gif

We at Finotes found this particularly interesting because one of the core capabilities of the SDK is to capture all kind of memory leaks occurring in an application in production. The R&D efforts of the engineering team focused on sweeping all aspects of Android to build a system that identifies memory leaks efficiently. The lightweight SDK is capable of capturing performance issues and bugs in production, the bug reports help you fix and optimize the app faster.

Mobile developers who are curious to learn more and experiment, visit finotes.com.

Write your comment…

Be the first one to comment