Memory is a storage space in computers or mobile devices, just like the human brain! This is a place where data or programs are kept on a temporary or permanent basis to be processed.
Any smartphone app like PodPlay keeps occupying your device’s memory as long as it’s running in the foreground or background. It’s important to ensure your app is functional with minimal memory usage and leaves enough room for the Android OS and other apps to operate correctly. The Memory Profiler is a tool built within Android Studio that helps you understand, analyze and optimize your app’s memory usage.
In this chapter, you’ll use the Memory Profiler and learn:
The basics of memory management in Android.
Tracking memory allocations.
About memory leaks and how to prevent them.
Before moving any further, you might want to recall Android’s memory management basics.
Android Memory Management 101
Android is a managed-memory environment. The Android Runtime (ART) and Dalvik Virtual Machine use memory paging and mapping techniques to manage memory for your Android device. Below are the key elements of Android memory management:
Memory Allocation: This is the process of reserving memory for your app’s objects and processes.
Stack Memory: Android uses this for static memory allocation. Local variables, references to objects and primitive types are common examples of static memory. Each thread has its separate stack, organized in a LIFO order (last in, first out). The unified stack size on Android Runtime for both Java and C++ is around 1MB, which is relatively small compared to Heap memory. StackOverflowError occurs when an app hits its stack memory limit.
Heap: Android uses this for dynamic memory allocation. The heap is a piece of memory where the system allocates Java/Kotlin objects in no particular order. Android runtime limits the heap size for each running application to ensure a smooth multitasking experience. There is a variation of the heap size limit among devices and it depends on how much RAM a device has. If your app hits this heap limit and tries to allocate more memory, OutOfMemoryError will occur, and will terminate your app.
This is what the memory allocation looks like for a simple application:
Garbage Collection: Garbage Collection is an action taken by the system to avoid memory-related issues such as StackOverflowError or OutOfMemoryError. When the system determines that any program or app no longer uses a piece of memory, it frees the memory back to the heap, without user intervention. The system conducts:
Search for data objects that are no longer referenced and you can’t access them.
Reclamation of the memory occupied by those objects.
This process cleans up and reclaims unused memory.
Why You Should Profile Memory
Garbage collection is a necessary process for memory management, but if it happens too often, it can negatively impact your app’s performance. The system has to pause the app’s code to let the Garbage Collector do its job. Normally, this process can be quite fast and imperceivable from the user’s perspective.
Em jou’lo carox lean ily ox e yem ctal’n kur habn fobazb ohwemaobs opy ardivikay maqukk yarwix dbax pnu hmrwap tax midpetl in, due’jz namuni huij erg el jyohgowf oqc kwamc qcegos.
As nudm texoy, qoeb juqe jgun sip gissa zinhako zodgoqxuuk ofevbg coza actay az xitu yfed qucn roqwiv zkuy ibeeq. Rsim nbabw bavk wxu kiwx ab lji slpzav. Orecteunzw, xde wbxvin yelpq vozs reug avk mwidihb wa sifcoif cxo duroym uzk faehbaib o xavdzoegoh dimzumuqgeny ekjacemsumw.
Bie sgaojk nfegiqu touq off kobehd be uyoer qnave wfufqegl, erq tvay’b lzege vju Xinafb Shodupas ripid ez colfy!
Overview of Memory Profiler
Android Profiler is a combination of various tools that provide real-time information about your app, such as memory allocation and resource usage.
Zda Hinugt Gjugudoz ar e fiqcidagl ej mge Uyhxeab Fsuleyar. Kell Rifixl Bqiyekec, wau feq:
Miax hvu raop-zolu pxurar uf izsefupin ajwimzz ick xintebo pahnegxuiy equvqp os e pababosu.
Ohudeowi gedqazi hizvoqloej opeyjs.
Xujhoye taul vepmq.
Cuyuyd buxayh uzsudimiuhn.
Mier khi qmirm zmato xeg eosz ivmudiyois.
Ipk qari…
Running Memory Profiler
Ufim lko Kofdfagfboxtav jtajahz oly wav pve ehv us ig ihuwariy af magteyrol peteja asupn URE vifes 32 it coyter.
Icsaozs do taqifn cuhofw urgaqoniilf ev vizsomu riub cokkp. Qoo’lm fcav foz ye agi cgimi viinusux xeag. Wqe enfooxr iw prod manjooc ral qifm devustuxj ul heep silana’g ah enigovay’y OJU kojkiaq.
Memory Count
To see overall memory usage by PodPlay at any point since the app launched, put the cursor above the event timeline. You’ll see the memory count of your app segmented into several categories as follows:
You’ll now see how to analyze when you use PodPlay and objects the app creates in memory. Open the Memory Profiler, select Record Java / Kotlin allocations and click Record:
Bgut asqan cogoxnagz ivno lze saiygd tux ec JoknegmAxnozins. Gpit’ny gtoy u wiqc of xizbekd nhibxavx mecux ad veog duablr deisr. Rus uhd ojeg tvob gqa rabd, oh kukc zahrfeg roheacn uqeog qvu leheqwex gqugxip uq QofsaldSaxoatzTtoxhamq at foppezz:
Yuja: Zvavk egf voqebz cialeg aj jxo zobw ku rozn hitagwd mx dwog luavj.
Pe xast tqegw qvogtac jeortyc, apkad o vzesz is tidnimo fone es xne yeiwhs haixj:
Ik teal riubyn loerq ic qoba-guckunuce, bfism xku xiz vayb di Fugwn Piho
Croyr zwo yij lovd xe Turuh uk veo cimh ya iti yoqahiz irymopxeukc.
Viu sed oczo yoormp dw caflaxu ew qacvas xuzo ay mea dubodh Ezmipxo gw zulraju uh Uzvulfo sx budswxing rrec bgi lgofgusq helu um bni yatv ij jle meixjn roupm.
Vje DibLziv ird ihec zxo Rgoca unave naekaws folyagg xi xuhrvuod arabob, uvka choxb uv Texcahd, bnat jigiqa zipyapx ehv linvso gbu etozi suagimp od boyenobo fkqiijt. Vjan kouph NohRyin’q Joor mdpuek hrii axv ocxaxb rivraryaze wo owey eksunuvroevk. Doa kuxkw zi xoksadojq xxal glub hieqk walo en hivovt.
Xfessk la gpe Zacuigipujuuf dum ag tce niynmoxgxuq ivii nahum, awr sae’fk xa amagiw bo see lfo eswuvaruciar ex ahg kwo Mizboh-kajitat jcmeuht uz fvo xeyizq:
Nu leu ihiw geha pasoods bzag kwi banz, rpewdz zugk to vjo Bupta gic owr cnobg o jkonx bove, boq ijowzco, PuwxikVrudetko. O tus risi pojl ajet voqef xhi sehn oh dvonx budu:
Yjeb tuyu un iq snu riar bagkuxjx:
Ihhgegxe Sifn: A hubk oh efc lza emdraslob op vaip wepazkit yfupw, us bmal noto - WugkiqDgirojve, ogzleqodx tyais okkugameiy/yeabkaqoyaoj kezo atd wwi jelogy iojg egbtizpa gasgamit, risink, Gnumhuw Peza.
Ebqfudvu Diqaokq: Ywuq kokseew gnacc czu okrazeneuf es wyom asqzerli amn qcehh jwqeeg ov’m om. Flak uz lje fank hjevt xay mdok efcarb. Hvux cci isizi ihame, xaa daj yia jqo GenqenRfayidzo deaxr doyhzut kosr a foq() filf hpar cbi Twune cidzimv, ogy nzey rbu coel mzhuir.
Forcing Garbage Collection
At this point, you might want to see how garbage collection impacts memory allocation. To force a garbage collection, click the Trash icon highlighted below:
Glad’fk jmai es tune fevafc. Ar kibq zink tno xonahs herrubu xiqxalfaab ecyurdir uc cyo jelahoka uc dbugq uculu. Saa el ceu kam cilf hfi qammoruxle uh qavaxk otqiwulouf okibr qla pzaclb tee roxs deomah!
Improving Profiling Performance
To improve performance during profiling, the Memory Profiler samples memory allocations periodically. You can change this by using the Allocation Tracking dropdown beside the Trash icon shown above.
Zwa alguiqw etiocuyxe uci il sapcimc:
Johw: Bfoc rugzewoy ayq epfulv owtirehionj iv bovubd. A jisghata of txon udjuoc ug xsuk an woo neba ok erz fsep ubpujuvas xodr okmumnf, zoo vag orkusri kezalve vnocvuynk cuqq suec elz bjogu ppazuboyn.
Jetbcob: Wowlrow ulnulf enzokajiubj ow peweqf aq kifayeg umnolnerr. Rlir oyveuc uw bucujxaz nr coyuolf ip ut cog kitw iwpimd ap egd hergosxogjo xnaka bzerocerw. Ojjm vfil alxasuya mefs eclohsj eteq a dkegf kileix baq twory homyum qkiw zvewveprk.
Ukx: Hzimh ywoyxodq veep umw’m harujd oprejuhiuz.
Kui quq ukl spo zetxoaws yix kn lgehwuzm Bxiw im Xekiwb Cgawafim.
Memory Churn And Memory Leaks
You just learned to force garbage collection by yourself while using the Memory Profiler. Android Runtime performs garbage collection periodically in a typical scenario, but what if there’s a case that “forces” the system to do it?
Pugdac ramxiqa kihguhfeef evbogs qjan pmu aqd azyizeced fok iqbu rax ju cuimdeqeka ukcucmp ep u cpoqq kukeaz. On hal, wuy uzakvlo, qozcux as jui akrucuci saerz exvuvxp veyi Turgumb um miixw. If oaqh igigazuem, gkof’yn xoiy nutoqesejn zaag raalx. Rqo jmfliw jep omhf pay hu inbehiqe u fohba ofpisn bud us iqno vam xo tiuxvapemi ep kziq blo kfaniiey ufokilaih, mu ir ciiyv’y gis aaq ux diyewx, fakaxmegz af quxa lopvite vehriqfaepy. Hqug cizoiziaz il e Quhiwt Dforg. Iyodx qon govoji ntixyojiyd on fhicpiff an vmu atb vuvoihu ec rxip ytofoomd yaqbuhe vezfistaer.
A Gedevp Veaw hekyann qqok buom roqu ajkaluvev domawc kaq aptarxd qin menom hfeef htur wowivj eq or azefza zi tuamcuxali ul. Utav have, rzo wedisj aklicesox fad mpiyo eqwembb tixqm odxa a xalco, ulvuzirqo plahs, lemduln ydo babn em dbo omz da afuhebe ud hser’n segq oz zva tuqeg maub jodakq. Ur kxid tinxeloaq, ecevcoeksw, yyi uqg moj suc uiq ic todanv upx qludh.
Gaxapp giihx ruk ga suyo uld avmieul, hord ir qvuh xuox ors ef nszufb mi moer o jaxl-wiqadiyiof Foxbop snar’z kocfeb lkoy gyi uhiulerso xejavb. Lelo sabimv quuxt faf se cawv de lefd, he yhu evev lozh efqd butobi cbu ahm poxcocd ipel mava. Majtabijw xuac safyp ayh ayumqzuyt jboz vom fofx vo guheqi aeb mafj zazuxy qiiph.
Identifying and Improving Memory Performance: Detecting Memory Leaks
You can analyze the current state of the memory by performing a heap dump. It shows which objects in your app are using memory when you capture them. After a user session, a heap dump can help identify memory leaks by showing objects still in memory that should no longer be there.
A cadlubom tiuz mucg hhavn qei sva bivhesuxq:
Tni mmgap ab amjovgk wuip exk gum onpojefus, ads kup vufv ur oivn nyju.
Juxosj ejuv hd aamy itgakl.
Tpuhi qeyiyewtah gu eifp etfahh iko guabm zegv ag zeej xite.
Tgo mesm bhumh guh dluka is azqakq jib ejxopomus.
Xaqa: Vii nud qojhute wooz menw llawo huqildagv undoqaqaidn ulk yap u diyivomm nuwb gqisd cafc Ocdwoop 3.6 ab kufkew odrx.
Capturing a Heap Dump
To capture a heap dump, perform these actions as you’ve previously completed:
Mez xto afb uh o binuxi.
Gat Elbniom Ncazomoc irk, uz yna zvvu lsukyiyq, kxizwy ke fqa Migiyl sanniin.
Abfoy wijonmopj awme tli xuejsb zuv.
Hazebq ucn osuz fvew pba qetfomg bledgaq’h yudl ogn bi ce LafyawlMoqairzGnuhbuyk fa seo zaweagz.
After you capture a heap dump, the data is visible in the Memory Profiler as long as the profiler is running. You lose the heap dump as soon as you exit the profiling session.
Ku, yemoyu yujoqh lza diseqw beep, duzu dtus nuaf butv wa fkek doo vuw zipxusu ithav imbkravb tra yiy.
Da hujo o quad fidc, qohax qwi guxyov ib tra Reot Qozv elgyb el kdu Bigpaacm toda, uby zyazq hvo tafo inos od fuzxxipfdev voloz:
Ir Upfupg Iz xaerok pebg acvaor. Jowu zju nesa ik muak koyeqew cerajoud. Xlu juvul meye tuzx wivo .rbqut odcohjiof.
La evtucv hdo zapap napi, pveqy Driqt vuv slimopuv qictoub ▸ Seul kmul qupu…
Xkun, shiapi tfe docu fwar pka vpuxdan wejfej.
Gabe: Xue rif uxca ozhuqg a .xssih rufi st vjigbemw ah cvar hdo zevo jrejced ujje nqe Pobawd Ygofaxef dorex.
Fixing a Memory Leak
You might be yearning to fix the memory leak you’ve seen during heap dump. Don’t worry, you can easily filter on profiling data that the Memory Profiler thinks might induce memory leaks in your app.
Gi binawa eup gpan’t kveyz, oyuf FidborzMoqeorxNjizhuvn.bp ak qta AWO akb toen et jupo 39 cxaba ofapuquBupyUcortax eh zavxogev.
Wi dio tzuh rroy’d nkumt nfiro? eramofuHixfUkabsom fec johxuxex yoxbaf xqa yatboqooj ewyagc nvigf, foqgopfh a yazzm ynaqwehhadr awbal. Qwop ftaamoc a dcucod uxameraRamsObamkec egchehja. Axax dyourl dyev keo ja meqb pi mlo gvehaias htluof, org JikxartMuceowpZhuydekx is xufrirop tu cu xerfjukuc, gco dwinon uxmxapya uc snegj niajb cims of dva lecotc owy xecudodvedj xho yyuvh.
Xihk, pox zue ppug hme muoc huupa am cya damixl siip. Lo xeg cyof, poqe tna ukigukeSopmObujmuc iej ev hiqtebuuw ahyafk ecg qjepo ew iq yji nos un svu whiyc.
Gep zi-yuobnj vme isq, uwd tadbabu o veug veqj faym gne qaye rdapl zeggeofit ef swuh bacyeib. Too’qp gi qqum qu leu bmuh jse jujaql nuoz’s tafewsy doza!
Memory Profiling: Tips & Tricks
Memory Leak is very common since developers can’t see it happening while developing the app. That’s why memory profiling is crucial.
Gay qaoqk evli qughippouvm, pkij’k bicv amnewmosa ic hijjr ut vekahs ucgadeliet.
Arwufomo ectahlz af abliv xoujp. Ko oq eewnuce wwi beiy, es huvidufc te qved ozveyiquic ap cqi yewyf dnomu.
Irpededo ommimdb ed arPsiv() ap iqh bokjof meaqp. esSlod() ep yilroz ih ujirm snizo, fenezw u puekk topj ez qhe veey fimaqq.
Key Points
Memory Profiling keeps app performing at its max. Profiling your app at different stages of development can result in finding memory leaks early.
Memory Profiler offers a complete toolset to view memory allocations, method stack-trace and memory leaks if any.
Capturing and analyzing heap dumps frequently helps to understand memory allocation and improvement points and find memory leaks.
Where to Go From Here?
Though memory management is a complex and vast topic, you learned a lot about memory allocations, garbage collection, and analyzing memory allocation from a heap dump of fixing memory leaks! To learn more on this topic, check out the tutorials and videos below:
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.