<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kareem Essam on Medium]]></title>
        <description><![CDATA[Stories by Kareem Essam on Medium]]></description>
        <link>https://medium.com/@kareemessam.me?source=rss-b05d070021a9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1NRmelwP2Ddczf6s4hrC1A.jpeg</url>
            <title>Stories by Kareem Essam on Medium</title>
            <link>https://medium.com/@kareemessam.me?source=rss-b05d070021a9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 19:33:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kareemessam.me/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[From XML to Pixels: The UI Rendering Pipeline (Part 3)]]></title>
            <link>https://medium.com/@kareemessam.me/from-xml-to-pixels-the-ui-rendering-pipeline-part-3-bbfd257215d8?source=rss-b05d070021a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbfd257215d8</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[rendering]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Kareem Essam]]></dc:creator>
            <pubDate>Mon, 02 Feb 2026 13:48:43 GMT</pubDate>
            <atom:updated>2026-02-02T13:48:43.854Z</atom:updated>
            <content:encoded><![CDATA[<h4>Unlocking the secrets of VSYNC, the GPU, and the 16ms Rule.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bY2QXPt54zBrsBfjuJUqng.png" /></figure><h3>Introduction: The Blank Screen</h3><p>In <a href="https://medium.com/@kareemessam.me/from-kotlin-code-to-apk-what-actually-happens-when-you-press-run-part-1-88aaded04719"><strong>Part 1</strong>,</a> we compiled our code.<br>In <a href="https://medium.com/@kareemessam.me/from-icon-click-to-oncreate-the-zygote-process-app-startup-part-2-bbc3e2c96a31"><strong>Part 2</strong></a>, we forked the Zygote and launched the app process.</p><p>We are now inside Activity.onCreate(). We called setContentView(R.layout.activity_main).</p><p>But if you could freeze time exactly at that millisecond, the screen would still be black.<br>The CPU knows <em>what</em> you want to show (a Button, a Text), but the screen doesn’t know <em>how</em> to light up the pixels yet.</p><p>How does a tree of Java/Kotlin objects turn into a smooth 60 Frames Per Second animation?<br>I dug into the graphics subsystem to find out, and I learned that Android is basically a highly coordinated dance between the CPU and the GPU.</p><h3>1. The Blueprint: The View Hierarchy</h3><p>When we write XML or build a Compose UI, we are creating a <strong>Tree</strong>.</p><p>The root is usually a DecorView (provided by the Window), and inside it, we have our ConstraintLayout, TextViews, etc.</p><p>Before a single pixel is drawn, the CPU must traverse this entire tree three times. This is called the <strong>View Traversal Steps</strong>:</p><p><strong>Measure Pass:</strong> The system asks every view: <em>“How big do you want to be?”</em></p><ul><li>The parent tells the child its limits (“You can’t be wider than 300dp”).</li><li>The child calculates and replies (“I need 50dp height”).</li></ul><p><strong>Layout Pass:</strong> The system tells every view: <em>“Okay, sit at position (x, y).”</em></p><p><strong>Draw Pass:</strong> This is where it gets interesting. The system doesn’t “paint” yet. It asks the view to generate a list of drawing commands.</p><blockquote>Concept Deconstructed: Wrap_Content is Expensive<br><em>I learned that </em><em>wrap_content isn&#39;t free. It forces the system to calculate measuring twice or more (Parent asks Child, Child asks Grandchild, Grandchild replies, Child re-calculates, replies to Parent). Deeply nested hierarchies with </em><em>wrap_content kill performance because of this recursion!</em></blockquote><h3>2. The Artist: DisplayLists &amp; The GPU</h3><p>In the old days (Android &lt; 3.0), drawing was direct. The CPU calculated the color of every pixel. It was slow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n7AdhJqjqjWm0sjKo6zylw.png" /></figure><p>Modern Android uses <strong>Hardware Acceleration</strong>.<br>Instead of the CPU painting pixels, it acts like a “Recording Director.”<br>During the <strong>Draw Pass</strong>, the CPU creates a <strong>DisplayList</strong>.<br>It’s a compact list of commands:</p><ul><li>“Draw a red rectangle at x,y.”</li><li>“Draw text ‘Hello’ here.”</li></ul><p>The CPU sends this list to the <strong>GPU (Graphics Processing Unit)</strong>.<br>The GPU is a math beast. It takes that list and executes it in parallel, turning commands into actual colored pixels on the screen (Rasterization).</p><h4><strong><em>Why is this faster?</em></strong></h4><p>If you move a button (animation), the CPU doesn’t have to redraw it. It just updates the <em>position</em> in the DisplayList, and the GPU simply renders the same button in a new place.</p><h3>3. The Conductor: VSYNC &amp; The 16ms Rule</h3><p>This was the biggest “Aha!” moment for me.<br>Why do we always hear about “16ms” in performance talks?<br>Most phone screens refresh <strong>60 times per second</strong> (60Hz).</p><p>→ 1000ms / 60 frames = 16.66ms</p><p>This means the system has a strict deadline. Every <strong>16.66ms</strong>, the screen <em>will</em> refresh. It doesn’t care if your app is ready or not.<br>To coordinate this, the system sends a signal called <strong>VSYNC (Vertical Synchronization)</strong>. Think of it like a metronome or a train leaving the station.</p><ul><li><strong>Tick:</strong> VSYNC fires.</li><li><strong>Work:</strong> CPU measures/layouts, GPU draws.</li><li><strong>Tock:</strong> 16ms later, the screen updates.</li></ul><blockquote>Concept Deconstructed: Jank (Dropped Frames)<br><em>If your code (e.g., a heavy loop in </em><em>onBindViewHolder) takes 20ms to run, you missed the train. The screen refreshes, but your new frame wasn&#39;t ready. The screen shows the </em>old<em> frame again.<br>To the user, the app “stuttered.” That is Jank.</em></blockquote><h3>4. The Choreographer</h3><p>How does the app know when the VSYNC signal fires?<br>There is a class called <strong>Choreographer</strong>.</p><p>When you ask for an animation (like View.animate()), you aren&#39;t moving pixels immediately. You are effectively telling the Choreographer: <em>&quot;Hey, put me on the list for the next frame.&quot;</em></p><p>When the hardware VSYNC signal hits, the Choreographer wakes up, alerts the Main Thread, and says: <em>“Go! Measure! Layout! Draw! You have 16ms starting NOW!”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LMtWs6S58o7dpIYZ00IDEw.png" /></figure><h3>5. Double Buffering: The Magic Trick</h3><p>Have you ever wondered why you never see the screen “half-drawn”?</p><p>It’s because Android uses <strong>Double Buffering</strong>.</p><ul><li><strong>Front Buffer:</strong> What the screen is currently showing.</li><li><strong>Back Buffer:</strong> What the GPU is currently drawing.</li></ul><p>The GPU draws silently on the Back Buffer. When the VSYNC signal hits (and the frame is ready), the system simply <strong>Swaps</strong> the buffers. The Back becomes the Front instantly.</p><p>If you miss the VSYNC window, the swap doesn’t happen, and the user sees the old Front Buffer again.</p><h3>My Takeaway: Why Native Feels “Buttery”</h3><p>This pipeline explains why Native Android feels so responsive.</p><p>We aren’t just throwing pixels at a canvas. We are participating in a highly synchronized system where:</p><ol><li><strong>D8/R8</strong> optimizes the code size.</li><li><strong>Zygote</strong> pre-loads the resources.</li><li><strong>DisplayLists</strong> offload work to the GPU.</li><li><strong>Choreographer</strong> aligns everything to the hardware refresh rate.</li></ol><h3>Conclusion: The Journey Ends</h3><p>We started with a line of Kotlin code.</p><p>We watched it compile into DEX, get packed into an APK, cloned from a Zygote, and finally rendered by the GPU onto the screen.</p><p>Understanding this journey hasn’t just made me a better debugger; it’s made me appreciate the platform I work on every day.</p><p>Next time you hit “Run,” remember: it’s not magic. It’s engineering.</p><h3>References &amp; Further Reading</h3><ol><li><strong>Android Developers:</strong> <a href="https://developer.android.com/topic/performance/rendering/profile-gpu">Profile GPU Rendering</a></li><li><strong>Android Internals:</strong> <a href="https://source.android.com/docs/core/graphics/architecture">Graphics Architecture (SurfaceFlinger)</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbfd257215d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Icon Click to onCreate: The Zygote Process & App Startup (Part 2)]]></title>
            <link>https://medium.com/@kareemessam.me/from-icon-click-to-oncreate-the-zygote-process-app-startup-part-2-bbc3e2c96a31?source=rss-b05d070021a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbc3e2c96a31</guid>
            <category><![CDATA[mobile-apps]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Kareem Essam]]></dc:creator>
            <pubDate>Fri, 02 Jan 2026 18:57:48 GMT</pubDate>
            <atom:updated>2026-01-02T18:57:48.802Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why Android doesn’t just “open” your app, and the genius behind the Zygote.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PUqEd5M0_WK0J9K8Kzqw-A.png" /></figure><h4>The Split Second</h4><p>In <a href="https://medium.com/@kareemessam.me/from-kotlin-code-to-apk-what-actually-happens-when-you-press-run-part-1-88aaded04719"><strong>Part 1</strong></a>, we saw how our Kotlin code was compiled into a neat .dex file and packaged into an APK. The app is installed. It&#39;s sitting in the device storage.</p><p>Now, I tap the app icon.</p><p>Boom! The splash screen appears almost instantly.</p><p>But wait… if Android is based on Linux/Java, shouldn’t there be a “boot up” time? On my laptop, launching a heavy Java application takes a few seconds to load the JVM (Java Virtual Machine) and libraries.</p><p>How does Android do it so fast?</p><p>I dug into the Android internal architecture, and I found the answer in a process with a very strange name: <strong>The Zygote.</strong></p><h3>1. The Problem: Starting from Scratch is Slow</h3><p>If Android worked like a standard desktop OS, every time you tapped an app icon, the system would have to:</p><ol><li>Allocate memory for a new process.</li><li>Start the ART (Android Runtime) from scratch.</li><li>Load all the core Android Framework libraries (Activity, View, String, etc.).</li><li>Finally, load your app code.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZIYhxGgiXWA2EYDrXQwKAA.png" /></figure><p>Steps <strong>2 and 3</strong> are heavy. If the phone did this for every single app, opening WhatsApp would take 3–5 seconds every time. The User Experience (UX) would be terrible.</p><p>Android solved this with a concept borrowed from biology.</p><h3>2. Meet “The Zygote”</h3><p>In biology, a Zygote is the initial cell formed when two gametes join — it’s the cell from which all other cells divide.</p><p>In Android, the <strong>Zygote Process</strong> is the “Parent” of every single app on your phone.</p><p><strong>How it works:<br></strong>When you boot up your phone (Android Logo animation), the OS starts the Zygote process immediately.<br>The Zygote does the heavy lifting once:</p><ol><li>It initializes the ART (Android Runtime).</li><li>It pre-loads all the common Android framework classes and resources (Drawables, Colors, Styles) into memory.</li><li>Then… it just waits. It opens a <strong>Socket</strong> and listens for requests.</li></ol><p>It creates a “Template Process” that is <strong>warm</strong>, loaded, and ready to go.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ov0bGZ6UDYSCy2zo" /></figure><blockquote><em>Concept Deconstructed: The Warm Start<br>Think of Zygote like a bakery that bakes a thousand plain distinct dough bases in the morning. When you order a pizza, they don’t start making the dough from flour and water. They grab a pre-made base (Zygote), throw your specific toppings on it (Your App Code), and bake it. It’s instant.</em></blockquote><h3>3. The “Forking” Magic</h3><p>When I tap my app icon, the system doesn’t create a “new” process. It Clones the Zygote.</p><p>It uses a Linux system command called <strong>fork</strong>().</p><p>The Zygote splits into two. The “Child” process inherits everything the Zygote already loaded (the ART, the framework classes).</p><p>Because the memory is already there, this cloning happens in milliseconds.</p><p>Once cloned, the new process loads my specific code (MainActivity, MyResources) on top of the inherited memory.</p><blockquote><em>Concept Deconstructed: Copy-on-Write (</em><strong><em>COW</em></strong><em>)<br>You might ask: “If every app copies the Zygote, doesn’t the RAM fill up instantly?”<br>No! Android uses a smart Linux feature called Copy-on-Write.<br>The Child process (My App) and the Parent (Zygote) actually share the same physical RAM for the common framework resources. The system only allocates new RAM when my app tries to modify something or load its own unique code.<br>This is why you can have 20 apps open and not run out of memory immediately.</em></blockquote><h3>4. The Sequence: What Happens When I Tap?</h3><p>So, putting it all together, here is the relay race that happens when I tap the icon:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k-diebaWJo4Drw9yexVpzA.png" /></figure><ol><li><strong>The Click:</strong> The Launcher App sends an Intent to the <strong>System Server</strong> (specifically, the ActivityManagerService or AMS).</li><li><strong>The Check:</strong> AMS checks: “Is this app already running?” (If yes, just bring it to front).</li><li><strong>The Request:</strong> If not, AMS connects to the <strong>Zygote Socket</strong> and says: “Hey, I need a new process for com.kareem.myapp.&quot;</li><li><strong>The Fork:</strong> Zygote calls fork(). A new process ID (PID) is born.</li><li><strong>Specialization:</strong> The new process is generic at first. It now renames itself to com.kareem.myapp and sets up its own sandbox (UID) so it can&#39;t touch other apps&#39; data.</li><li><strong>The Entry Point:</strong> The system calls ActivityThread.main().</li></ol><h3>5. Start Types: Cold, Warm, and Hot</h3><p>Now that we know the process, we can understand why performance varies.</p><ul><li><strong>Cold Start:</strong> This happens when your app isn’t in memory at all (e.g., after a reboot or if the system killed it to save RAM). The system must Fork the Zygote, create the process, and initialize ActivityThread. This is the slowest start.</li><li><strong>Warm Start:</strong> The process is already created and sitting in memory, but the Activity was destroyed (e.g., you backed out of the app, but didn&#39;t force close it). The system just needs to re-inflate the layout.</li><li><strong>Hot Start:</strong> The app is already running and the Activity is still there (e.g., you just switched to another app and switched back). The system just brings the window to the foreground. Instant.</li></ul><p><strong>Tip:</strong> As developers, we optimize for the <strong>Cold Start</strong> because that’s the “worst-case scenario” for the user.</p><h3>6. The Real Entry Point: ActivityThread.main()</h3><p>I always thought onCreate() was the first method to run. <strong>It&#39;s not.</strong></p><p>Java programs always start with public static void main(). Android apps are no different. The real entry point is inside a hidden class called ActivityThread.</p><p>When ActivityThread.main() runs, it does two critical things:</p><ol><li><strong>It prepares the Looper:</strong> This is what initializes the <strong>Main Thread</strong>. Without this, your app couldn’t process UI events or button clicks.</li><li><strong>It binds the Application:</strong> It tells the system “I’m ready.”</li></ol><p>Only <em>after</em> this setup does the system call mInstrumentation.callApplicationOnCreate(), which triggers the Application.onCreate() function you override in your code. Then, finally, MainActivity is launched.</p><h3>My Takeaway</h3><p>Before this deep dive, I thought optimization was just about writing clean Kotlin loops.</p><p>But realizing that every app is a “Clone” of a master process changed how I think about static variables and memory.</p><p>The OS does an incredible amount of heavy lifting (Forking, COW, Resource Sharing) just so our apps can launch in under a second.</p><p>But we aren’t done yet.</p><p>The app is running. The onCreate happened. But the screen is just a blank window. How does the XML I wrote actually turn into pixels? What is a “Window”? And why does everyone talk about 60 FPS?</p><p>In <strong>Part 3</strong>, we will explore the <strong>UI Rendering Pipeline</strong> (Measure, Layout, Draw) and how the GPU paints the screen.</p><h3>References</h3><ul><li><a href="https://developer.android.com/guide/components/processes-and-threads">Android Process Management (Official Docs)</a></li><li><a href="https://www.google.com/search?q=https://cs.android.com/android/platform/superproject/%2B/master:frameworks/base/core/java/com/android/internal/os/ZygoteInit.java">Zygote and System Startup (Android Source)</a></li><li><a href="https://en.wikipedia.org/wiki/Copy-on-write">Copy-on-Write (Wikipedia)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbc3e2c96a31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Kotlin Code to APK: What Actually Happens When You Press “Run” (Part 1)]]></title>
            <link>https://medium.com/@kareemessam.me/from-kotlin-code-to-apk-what-actually-happens-when-you-press-run-part-1-88aaded04719?source=rss-b05d070021a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/88aaded04719</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[Kareem Essam]]></dc:creator>
            <pubDate>Fri, 26 Dec 2025 16:39:17 GMT</pubDate>
            <atom:updated>2025-12-26T16:39:17.829Z</atom:updated>
            <content:encoded><![CDATA[<h4>A deep dive into the Android Build Process, D8, R8, and why Native is fast.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZcYqqapP9a2NtuhTwYcQQg.jpeg" /></figure><h4><strong><em>Introduction</em></strong>: The Magic Button</h4><p>As Android developers, we press the green <strong>Run</strong> button dozens of times a day. It feels like magic: we write Kotlin, Gradle spins for a few seconds, and an app appears.</p><p>But recently, I realized that treating the build process as a “black box” was holding me back. I knew <em>how</em> to write the code, but I didn’t truly understand <em>how</em> the machine executes it.</p><p>So, I decided to stop taking the tools for granted. I went down a rabbit hole of documentation and compiler logs to answer one specific question: <strong>How does a human-readable Kotlin file actually turn into an app running on a phone?</strong></p><p>— Here is what I found:</p><h3>1. The Architecture: Why Android isn’t “Just Java”</h3><p>It is easy to assume that because we write in Java/Kotlin, Android must work exactly like a standard Desktop Java application running on a JVM (Java Virtual Machine).</p><h4><strong>That assumption is wrong.</strong></h4><p>While digging into the OS architecture, I found that Android uses a completely different runtime environment called <strong>ART (Android Runtime)</strong>. The difference works like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M9p70Imus43RmtMvTXo3xQ.png" /></figure><ul><li><strong>Standard JVM (Stack-Based):</strong> It uses a “Stack.” To perform1 + 1, the CPU has to push and pop values constantly. It requires many small instructions.</li><li><strong>Android ART (Register-Based):</strong> Mobile devices need to save battery. ART uses “Registers” (specific slots). It simply says: “Add slot A to slot B.” It requires fewer instructions to do the same job.</li></ul><pre>// 1. Standard JVM (Stack-Based)<br>// Ideally requires 4 instructions involving pushing/popping<br>iload_0    <br>iload_1    <br>iadd       <br>ireturn    <br><br>// 2. Android Dalvik/ART (Register-Based)<br>// Requires fewer instructions, working directly on &quot;slots&quot;<br>add-int v0, v0, v1   // Add v0 and v1, store result in v0<br>return v0            // Return v0</pre><p><strong>The takeaway:</strong> Standard compiled Java code (.class files) is literally incompatible with Android phones. If you put a .class file on a device, the OS won&#39;t know how to read it.</p><blockquote>Concept Deconstructed: Opcode<br>An Opcode is the low-level instruction that tells the processor what to do. The key difference is that ART expects register-based bytecode, while standard JVM bytecode is stack-based. They speak different languages.</blockquote><h3>Step 1: Frontend Compilation (The .class Files)</h3><p>The journey begins when you hit Build. Since I use Kotlin, the kotlinc compiler kicks in.</p><p>At this stage, nothing “Android” is happening yet. The compiler checks for syntax errors (like missing semicolons) and converts the code into <strong>Java Bytecode</strong> (.class files).</p><p>These files are “Platform Agnostic” — they don’t know they are destined for a phone yet.</p><h3>Step 2: The “Dexing” Process (D8)</h3><p>This is where the Android-specific work begins. The build system uses a tool called <strong>D8</strong>.</p><p>D8 is a “Dexer.” It takes all the .class files (and the libraries used, like Retrofit) and compiles them into <strong>Dalvik Executable (.dex)</strong> files.<br>Why is this cool?</p><p>In standard Java, every class has its own file. D8 merges them all into a single pool and eliminates duplicates. This makes .dex files incredibly compact and efficient compared to a folder full of .class files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6SUQJu0A7DxPe1mudVyr5Q.png" /></figure><blockquote>Concept Deconstructed: The 64k Limit<br>Ever heard of the “64k Method Limit”? The .dex format uses an index to reference methods. Originally, this index was limited to 65,536 methods.</blockquote><blockquote>Modern Solution: D8 handles this automatically by splitting your app into multiple files (classes.dex, classes2.dex). This is called MultiDex.</blockquote><h3>Step 3: Shrinking &amp; Optimization (R8)</h3><p>A common question is: “If I include a massive library like Google Maps but only use one function, does my app size explode?”<br>The answer is No, thanks to R8.</p><p>R8 runs during the build and performs Graph Traversal:</p><ul><li><strong>Entry Points:</strong> It starts at your MainActivity.</li><li><strong>Tracing:</strong> It traces every function you call.</li><li><strong>Tree Shaking:</strong> If a class or function is never reached, R8 marks it as “Dead Code” and physically removes it.</li></ul><p>It also performs <strong>Obfuscation</strong>, renaming classes from com.myapp.UserHelper to a.b.c. This isn&#39;t just for security; shorter names save bytes!</p><blockquote><strong>Note:</strong> R8 usually runs fully only on <strong>Release</strong> builds. <br>In <strong>Debug</strong> builds, most optimizations are disabled to keep compilation fast and stack traces readable.</blockquote><h3>Step 4: Packaging (APK vs. AAB)</h3><p>We have the code (.dex) and the resources (images, XML). We need to package them.<br>In the past, we built a single <strong>APK (Android Package)</strong> that contained everything for every device. It was huge.</p><p>Today, we use the <strong>AAB (Android App Bundle):</strong></p><ul><li><strong>The Developer</strong> uploads an AAB to Google Play.</li><li><strong>Google Play</strong> acts as a factory. <br>When a user downloads the app, Google Play generates a “Split APK” containing <em>only</em> the resources that the user needs (e.g., only English strings and high-density images).</li></ul><p>This makes the download size significantly smaller.</p><h3>6. Performance: Why Native is Fast (JIT vs AOT)</h3><p>After understanding this pipeline, the “why” behind Native performance finally clicks. But there was one last piece of the puzzle: <strong>How does ART execute this code?</strong></p><p>Modern Android (Android 7+) uses a <strong>Hybrid Model</strong>:</p><ol><li><strong>JIT (Just-In-Time):</strong> When you first install the app, ART uses JIT to run code quickly without long installation times.</li><li><strong>Profiling:</strong> As you use the app, ART watches which methods you use most (Hot Methods).</li><li><strong>AOT (Ahead-Of-Time):</strong> When the device is idle and charging, a background service takes those “Hot Methods” and compiles them into pure <strong>Machine Code</strong> (Assembly).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I-V9Bf2ix69uhX3SZpSWig.png" /></figure><p>Next time you open the app, it runs directly on the hardware. No interpretation needed.</p><h3>What’s Next?</h3><p>Now that the app is installed, what happens when I tap the icon? How does the Android OS create a “Process”? And what is the “Zygote”?</p><p>I am currently reading about the Android boot process, and I will share Part 2 soon!</p><h3><strong>References:</strong></h3><ul><li><strong>Android Developers:</strong> <a href="https://developer.android.com/build/shrink-code">Shrink, obfuscate, and optimize your app with R8</a></li><li><strong>Android Source:</strong> <a href="https://www.google.com/search?q=https://source.android.com/docs/core/runtime/index">ART and Dalvik Architecture</a></li><li><strong>Android Source:</strong> <a href="https://source.android.com/docs/core/runtime/dalvik-bytecode">Dalvik Bytecode Constraints</a></li><li><strong>Android Developers:</strong> <a href="https://developer.android.com/guide/app-bundle">Android App Bundles Explained</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88aaded04719" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why C Makes You Take Out the Garbage Yourself!]]></title>
            <link>https://medium.com/@kareemessam.me/why-c-makes-you-take-out-the-garbage-yourself-7df19030bbe5?source=rss-b05d070021a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/7df19030bbe5</guid>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[garbage-collection]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[c-programming]]></category>
            <dc:creator><![CDATA[Kareem Essam]]></dc:creator>
            <pubDate>Wed, 11 Jun 2025 00:18:09 GMT</pubDate>
            <atom:updated>2025-06-11T00:18:09.467Z</atom:updated>
            <content:encoded><![CDATA[<p>I found it both funny and fascinating to dive into one of the most essential yet often overlooked concepts in programming: memory management.<br>With the rise of heavyweight AI models and the explosion of big data, memory efficiency is more important than ever.</p><p>I’ve always admired how smartly we (humanity, I guess? ) have tackled this challenge, especially the clever algorithms designed to optimize memory usage and prevent nasty leaks. So, here’s a light and brief exploration of how memory management works, how different programming languages “clean up your mess” (unlike C, which basically throws you into the sea and says, “Try to swim, babe.” ), and finally…</p><p><strong>The Baba Yaga of memory itself: the mighty Garbage, and its savior the Garbage Collector.</strong></p><h3>What Is “Memory” Anyway?</h3><p>Think of your computer’s memory as a giant hotel for data. Every time your C program runs and needs a place to stay, it checks in a piece of data, like a variable, into a specific room, a memory address in RAM.<br>This hotel has different “wings,” each with its own rules and guests, and I will mention just some:<br><strong><em>Heap:</em></strong><br>The wild west of memory. This is where you dynamically request space at runtime using functions like malloc(). It’s like booking an Airbnb — you get freedom and flexibility, but you’re also in charge of cleaning up (using free), or things will get messy (hello, memory leaks).<br><strong><em>Stack:</em></strong><br>A tightly run B&amp;B. Local variables get “pushed” onto the stack when you enter a function and “popped” off when you leave. It’s fast, neat, and self-cleaning — no need to tidy up yourself.<br>Want to go deeper? <a href="https://www.geeksforgeeks.org/memory-layout-of-c-program/"><strong>Check out this great visual explanation of C’s memory layout.</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*dlOw5EE8FcowhrYYa0A4dQ.png" /></figure><h4>Pointer Hotel!</h4><p>Imagine your variables are guests staying in memory — our big ol’ hotel. Each room has a number (a memory address), and each guest (a variable) is staying in one. <strong>So what’s a pointer?</strong><br>It’s like a clipboard at the reception desk. It doesn’t hold the guest itself — it just holds the room number where the guest is staying.</p><pre>#include &lt;stdio.h&gt;<br><br>int main() {<br>    int guestAge = 25;         // Our guest<br>    int *roomKey = &amp;guestAge;  // Clipboard holds the room number<br><br>    printf(&quot;Guest age: %d\n&quot;, *roomKey);   // Knock on the door and ask who&#39;s inside<br>    printf(&quot;Room number: %p\n&quot;, roomKey);  // The address of guestAge<br>}</pre><blockquote>&amp; = “Where’s the room?” (Get the address)<br>* = “What’s in the room?” (Get the value at that address)</blockquote><p>Want to go deeper into pointers? <strong>T</strong><a href="https://medium.com/@Dev_Frank/pointers-in-c-422cccdbf2f6"><strong>his Medium post by Dev Frank </strong></a>is a great read</p><h4>Garbage</h4><p>Imagine walking into a hotel room (a memory space) without checking in as a guest (a variable). You flip on the light expecting a clean room… but instead, you find a half-eaten sandwich, a haunted teddy bear, and someone else’s forgotten socks.<br>Welcome to the world of garbage values.</p><pre>#include &lt;stdio.h&gt;<br><br>int main() {<br>    int mysteriousGuest;  // No check-in, no cleanup<br><br>    printf(&quot;What&#39;s in the room? %d\n&quot;, mysteriousGuest);  // Might print 929303—or a goat emoji. Who knows?<br>    return 0;<br>}</pre><p><strong><em>What Just Happened?<br></em></strong>You declared mysteriousGuest but didn’t give it a value.<br>In C, memory isn’t pre-cleaned or initialized. So when you try to read from that room, you get whatever random junk was left behind — maybe from another function, maybe from another program… maybe from another dimension.</p><blockquote>Why Garbage Happens?<br>C is raw and unmanaged. When you declare a variable, it just grabs the first available room in memory. If you don’t explicitly assign a value, C won’t warn you — it just hands you the key and says, “Good luck.”</blockquote><p><strong><em>How to Avoid It?<br></em></strong>Always initialize your variables.<br>That way, your room is freshly cleaned and ready for your guest.</p><h4>Garbage Collector</h4><p>A garbage collector is a program (or part of a program) that automatically frees memory that’s no longer in use. It’s the behind-the-scenes janitor, constantly cleaning up after your code so you don’t have to.<br>Languages like <strong>Python, Java, JavaScript, and Go</strong> all use garbage collectors to manage memory while your program is running. This process is called automatic memory management.</p><p>Automatic memory management can be a massive productivity booster — it means less code for you to write and often fewer memory-related bugs to worry about. The trade-off? Performance. Since the garbage collector is always lurking in the background (kind of like Forrest Gump — always running), it can sometimes slow things down.</p><blockquote>That’s why languages like C, C++, and Rust, which give you manual control over memory, are still top picks when performance is mission-critical and every cycle counts.</blockquote><h4>Different Garbage, Different Bins:</h4><p>Not all garbage collectors clean up the same way. Just like real-life trash systems — some recycle, some ezzz and fast, and some just do the job no matter what — programming languages use different strategies to clean up memory.</p><p>Let’s take a quick tour through two of the most common methods:<br><strong><em>Reference Counting: </em></strong>simple and fast, but with a sneaky weakness…<br><strong><em>Mark-and-Sweep:</em></strong> a more thorough spring cleaning, but it comes at a cost.</p><p>Each has its own strengths, trade-offs, and quirks. So, let’s peek behind the curtain and see how these memory janitors really do their job.</p><h4>Reference Counting: The Guest Tracker at the Front Desk</h4><p>Imagine every memory “room” in our hotel has a clipboard at the front desk. This clipboard keeps track of how many guests (references) are using that room.</p><p>This is reference counting, a simple yet clever garbage collection method where each memory block keeps a count of how many references (pointers) point to it. When that count drops to zero, it means no one’s using the room anymore — and it’s time to clean it up.</p><p><strong><em>How does it work?</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*bvrJHbWX99lo1T9oyZ4y1A.gif" /></figure><blockquote>You allocate memory → Clipboard: “1 guest checked in.”<br>You copy the pointer → Clipboard: “Now 2 guests in this room.”<br>You release one reference → Clipboard: “Back to 1 guest.”<br>All references are gone → Clipboard: “Room is empty. Cleanup time!”</blockquote><p>As soon as the count hits zero, memory is automatically freed. That’s the beauty of reference counting — it guarantees cleanup happens right when it’s no longer needed.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br><br>typedef struct {<br>    int *data;<br>    int refCount;<br>} RefPointer;<br><br>RefPointer* create() {<br>    RefPointer* ref = malloc(sizeof(RefPointer));<br>    ref-&gt;data = malloc(sizeof(int));<br>    *(ref-&gt;data) = 42;<br>    ref-&gt;refCount = 1;<br>    return ref;<br>}<br><br>void addRef(RefPointer* ref) {<br>    ref-&gt;refCount++;<br>}<br><br>void releaseRef(RefPointer* ref) {<br>    ref-&gt;refCount--;<br>    if (ref-&gt;refCount == 0) {<br>        free(ref-&gt;data);<br>        free(ref);<br>        printf(&quot;Memory cleaned up!\n&quot;);<br>    }<br>}<br><br>int main() {<br>    RefPointer* guest = create();  // Room booked, refCount = 1<br>    addRef(guest);                 // Another guest moved in, refCount = 2<br>    releaseRef(guest);             // One leaves, refCount = 1<br>    releaseRef(guest);             // All gone, room cleaned<br>}</pre><blockquote>Reference counting is like the front desk handing out keycards.<br>As long as someone holds a keycard (a pointer), the room stays booked.<br>Once all keycards are returned, the hotel knows the room can be cleaned.</blockquote><p><strong><em>The Circular Trap:</em></strong><em><br></em>One major issue? Circular references. If A points to B and B points to A, their counts never hit zero, even if nobody else is using them. They cling to each other like clingy roommates, and the GC doesn’t know how to break them up.</p><blockquote>That’s why languages like Python or Swift combine reference counting with a cycle detector or a backup collector (like mark-and-sweep).</blockquote><h4>Mark and Sweep: The Smart Hotel Housekeeping</h4><p>Welcome to Mark &amp; Sweep Suites, where rooms aren’t cleaned right after checkout. Instead, we have an elite housekeeping team that does routine sweeps to find out which rooms are still occupied and which are gathering dust. This is Mark and Sweep Garbage Collection, a classic method used by many high-level languages.</p><p><strong><em>How does it work?<br></em>Mark Phase — “Who’s still checked in?”<br></strong>The system starts from root references (like global variables or the call stack). It walks through all objects reachable from these roots.<br>Each reachable object is marked as “still in use.”</p><p><strong>Sweep Phase — “Time to clean!”<br></strong>Now the system loops through all objects in memory.<br>If an object isn’t marked, it’s garbage — memory is freed. If it was marked, the mark is cleared for the next GC cycle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*L4WGutRBomHr2cl20vWi6g.gif" /></figure><p><strong><em>Hotel Analogy<br></em></strong>In this hotel, some guests might leave without checking out — no key return, no goodbye. So the hotel sends staff to knock on all doors connected to guests it still knows about (like those from main() or global variables).<br>If someone answers? The room is marked “occupied.”<br>No answer? The room is declared abandoned and swept clean.</p><pre>struct Object {<br>    bool marked;<br>    struct Object* ref1;<br>    struct Object* ref2;<br>    // ... other references<br>};<br><br>void mark(Object* obj) {<br>    if (obj == NULL || obj-&gt;marked) return;<br>    obj-&gt;marked = true;<br>    mark(obj-&gt;ref1);<br>    mark(obj-&gt;ref2);<br>}<br><br>void sweep(Object** heap, int heapSize) {<br>    for (int i = 0; i &lt; heapSize; i++) {<br>        if (!heap[i]-&gt;marked) {<br>            free(heap[i]);  // Abandoned room<br>        } else {<br>            heap[i]-&gt;marked = false;  // Reset for next round<br>        }<br>    }<br>}</pre><blockquote>In Simple Terms<br>Mark = “Who’s still alive?”<br>Sweep = “Remove everyone else.”<br>Unlike reference counting, cleanup doesn’t happen immediately — it’s done in periodic sweeps, but it can handle cycles (e.g. objects referring to each other).</blockquote><h4>Wrapping Up: Memory’s Detectives and Secret Agents</h4><p>From clipboard-wielding front desks (reference counting) to detective-style room inspections (mark and sweep), garbage collectors are the unsung heroes keeping our memory clean and our programs running smoothly.</p><p>Each technique has its quirks — some clean up instantly, others wait for the right time, and some even struggle with ghosts that never check out (looking at you, circular references haha).</p><p><strong><em>But here’s the takeaway:<br></em></strong>Understanding how memory is managed makes you a better programmer, whether you’re wrangling pointers in C, writing clean Python scripts, or optimizing Java performance.</p><p>So next time your code runs like butter, tip your hat to the invisible guardian in the background… <strong>The mighty Garbage Collector</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7df19030bbe5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>