<?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 Mohammad Mavia on Medium]]></title>
        <description><![CDATA[Stories by Mohammad Mavia on Medium]]></description>
        <link>https://medium.com/@mauwia.atif?source=rss-e9b59b1ae47------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wtwq5g4iTG3JstDT_U4FDQ.jpeg</url>
            <title>Stories by Mohammad Mavia on Medium</title>
            <link>https://medium.com/@mauwia.atif?source=rss-e9b59b1ae47------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 13:30:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mauwia.atif/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[Understanding Heap and Stack Memory Management in Go]]></title>
            <link>https://medium.com/@mauwia.atif/understanding-heap-and-stack-memory-management-in-go-5c8b1270c667?source=rss-e9b59b1ae47------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c8b1270c667</guid>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[heap]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Mohammad Mavia]]></dc:creator>
            <pubDate>Wed, 09 Oct 2024 07:07:53 GMT</pubDate>
            <atom:updated>2024-10-09T07:07:53.619Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r9fRtNaI7tybfZYnRZvS6A.jpeg" /></figure><p>In Go, memory management is crucial in optimizing performance, especially when dealing with large-scale applications. The heap and the stack are two primary memory regions, each serving distinct purposes for memory allocation and deallocation. Understanding how they work in Go is essential for writing efficient code. Let’s dive into how the heap and stack work in Go, their differences, and some key examples.</p><h3>Stack in Go</h3><p>The <strong>stack</strong> is where local variables, function call information, and control flow are stored. It’s a region of memory that works in a <em>Last-In-First-Out</em> (LIFO) manner. Every time a function is called, its local variables and parameters are placed on the stack. When the function returns, the memory is automatically freed.</p><h4>Key Characteristics of the Stack:</h4><ol><li><strong>Fixed Size</strong>: The stack has a fixed size that grows automatically as needed (up to a limit).</li><li><strong>Automatic Memory Management</strong>: Memory allocation and deallocation on the stack are done automatically, without requiring explicit intervention.</li><li><strong>Efficient Access</strong>: Accessing memory from the stack is faster due to its structured and predictable nature.</li><li><strong>Limited Lifetime</strong>: Stack-allocated memory only lives as long as the function is executing.</li></ol><h4>Example of Stack Usage in Go:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gi5wX6HQUPSVoXtQHABTyw.png" /></figure><p>In the above example, a, b, and c are stored on the stack, and when sum returns, that memory is freed.</p><h4>Stack Size Limitations:</h4><p>The stack size is relatively small compared to the heap, which is why it’s ideal for short-lived, simple data like local variables. However, recursion or deeply nested function calls can lead to a stack overflow if the stack grows beyond its limit.</p><h3>Heap in Go</h3><p>The <strong>heap</strong> is used for dynamic memory allocation. When variables need to outlive the function they were created in or when you don’t know how much memory is required at compile-time, Go uses the heap. Heap memory is managed through Go’s <strong>garbage collector</strong>, which automatically frees memory when it’s no longer needed.</p><h4>Key Characteristics of the Heap:</h4><ol><li><strong>Dynamic Allocation</strong>: Heap memory is allocated at runtime, making it suitable for dynamic data structures like slices, maps, and channels.</li><li><strong>Global Lifetime</strong>: Memory allocated on the heap can outlive the function it was created in.</li><li><strong>Manual Management</strong>: Although Go’s garbage collector handles deallocation, excessive heap allocation can lead to performance overhead due to GC pauses.</li><li><strong>Slower Access</strong>: Accessing heap memory is slower than stack memory because of its less predictable structure.</li></ol><h4>Example of Heap Usage in Go:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s61i-X8mnaKELqUg5zRaTA.png" /></figure><p>In this case, s is allocated on the heap because it is referenced outside of its function scope. The garbage collector manages this memory and will release it once it is no longer in use.</p><h3>Escape Analysis</h3><p>Go determines whether a variable should be stored on the stack or the heap using a process called <strong>escape analysis</strong>. If a variable <strong>escapes</strong> the local scope (e.g., it’s returned from a function or used in a closure), it will be allocated on the heap. If it doesn’t escape, it will remain on the stack.</p><p>Here’s a simple example to illustrate escape analysis:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*A7ru4H-I4iI9YSAfNk5VHg.png" /></figure><p>In this example, variable a escapes to the heap because it is returned from the function, meaning its lifetime must extend beyond the function execution.</p><h3>Heap vs. Stack in Go</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*2RuF41tso6KSiC_YyGbU-Q.png" /></figure><h3>Optimizing Stack and Heap Usage</h3><p>Go provides many built-in optimizations for managing the stack and heap efficiently, but there are several practices you can follow:</p><ol><li><strong>Minimize Heap Allocations</strong>: Prefer local variables when possible to keep memory on the stack. Excessive heap allocations can trigger frequent garbage collection, leading to performance bottlenecks.</li><li><strong>Analyze Escapes</strong>: Use Go’s built-in tools like go build -gcflags=&quot;-m&quot; to run escape analysis and see where your variables are being allocated (stack or heap).</li><li><strong>Manage Large Data</strong>: If dealing with large data structures, be mindful of how often they are allocated and deallocated, as this can impact the garbage collector.</li></ol><h3>Conclusion</h3><p>Understanding how the heap and stack work in Go allows you to write more optimized code. The stack is ideal for quick, short-lived allocations with automatic memory management, while the heap is used for more flexible, long-lived memory needs. By minimizing unnecessary heap allocations and leveraging Go’s escape analysis, you can improve performance and reduce the overhead caused by garbage collection.</p><p>If you’re dealing with performance-critical code, tools like pprof and go build -gcflags=&quot;-m&quot; can provide insight into how your memory is being managed and help identify optimization opportunities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c8b1270c667" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multithreading in Go and Rust: A Comparative Analysis]]></title>
            <link>https://medium.com/@mauwia.atif/multithreading-in-go-and-rust-a-comparative-analysis-8b11c00a8ec0?source=rss-e9b59b1ae47------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b11c00a8ec0</guid>
            <category><![CDATA[parallelism]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[multithreading]]></category>
            <dc:creator><![CDATA[Mohammad Mavia]]></dc:creator>
            <pubDate>Sat, 09 Sep 2023 08:46:49 GMT</pubDate>
            <atom:updated>2023-09-09T08:46:49.004Z</atom:updated>
            <content:encoded><![CDATA[<p>Multithreading is a crucial concept in modern software development that enables efficient concurrent execution of tasks. Two popular languages, Go and Rust, have brought unique approaches to the table in terms of multithreading. This article explores the fundamental differences in how these languages handle concurrency and parallelism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DGNJxEKO8Bz7Qg7_sJaz2A.png" /></figure><h3>1. Design Philosophy:</h3><h4>Go:</h4><p>Go, often referred to by its nickname “Golang”, adopts a high-level approach to concurrency with its goroutine mechanism. Goroutines are lightweight threads managed by the Go runtime instead of the underlying OS. The philosophy in Go is: “Do not communicate by sharing memory; instead, share memory by communicating.” This is embodied in the language by channels, which allow safe communication between goroutines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PGHTtWCFQS9i0pa8YX4K9g.png" /></figure><p>In this example, instead of sharing memory directly, a channel is used to pass a message between the main function and a goroutine.</p><h4>Rust:</h4><p>Rust’s philosophy is ensuring memory safety without sacrificing performance. Concurrency in Rust is achieved through various primitives like threads, channels, and atomic operations. The Rust compiler employs a powerful ownership system that guarantees data races are caught at compile time, a unique feature in the realm of system programming.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7HNkos3Aci9yEEpSCft3cg.png" /></figure><p>This Rust program won’t allow you to use v after it&#39;s been moved into the thread, preventing data races.</p><h3>2. Concurrency Abstractions:</h3><h4>Go:</h4><ul><li>Goroutines: These are lightweight and more memory-efficient than traditional threads. Starting a goroutine is simple with the go keyword.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0km8q4E9fRRaUN1U-Y4ITA.png" /></figure><ul><li>Channels: Channels provide a way for goroutines to communicate safely without using locks or other synchronization mechanisms. Channels can be buffered or unbuffered.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x5jzxPbgRhXhGPYGFjuPuQ.png" /></figure><h4>Rust:</h4><ul><li>Threads: Rust uses the standard library’s thread module for spawning OS-level threads.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DkLeDPu6C4SZcYptu4P3gA.png" /></figure><ul><li>Channels: Rust’s standard library offers channels similar to Go, providing a way for threads to communicate safely.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7sbakgeJD-U1-61NgQc6PQ.png" /></figure><ul><li>Mutexes, Atomics, and Arc: For shared mutable state, Rust offers Mutex (Mutual Exclusion) and atomic operations. The Arc (Atomic Reference Counted) type enables multiple threads to own a reference to some data.</li></ul><h3>3. Error Handling:</h3><h4>Go:</h4><p>In Go, if a goroutine panics (analogous to throwing an exception in other languages), it will crash only that specific goroutine and not the entire program. However, it’s crucial to handle such panics to prevent potential data inconsistency.</p><p>Capturing panic in a goroutine:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JDj8DD2FOpGoQhD8IsQqhg.png" /></figure><h4>Rust:</h4><p>In Rust, if a thread panics, it can be caught using the thread::spawn API, which returns a JoinHandle. By calling join on this handle, one can detect if the thread has panicked, thus ensuring that panics don&#39;t cascade through your system.</p><p>Capturing panic in a thread:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-CtKA_SO7vpWlTbB7_JvVw.png" /></figure><h3>4. Performance Overheads:</h3><h4>Go:</h4><p>The Go runtime takes care of scheduling goroutines on available OS threads. This brings some overhead but offers advantages like easier scalability due to goroutines’ lightweight nature.</p><p>A goroutine scheduler:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uh5xKS3Wj6Tf-dNuw7rsMg.png" /></figure><h4>Rust:</h4><p>Since Rust employs OS-level threads (unless you use external libraries), it might have a higher memory overhead than goroutines. However, it can offer better CPU performance in certain scenarios because there’s no extra scheduler in the middle.</p><p>Spawning multiple OS-level threads:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o_1qQDnACq4eiYqG3jDq3w.png" /></figure><p>(These examples are more conceptual, as directly showcasing performance can be tricky without benchmarks)</p><h3>5. Safety Guarantees:</h3><h4>Go:</h4><p>While channels offer a high degree of safety, Go doesn’t provide compile-time guarantees against data races. Developers need to be cautious and use tools like the race detector during testing.</p><p>You’d typically use the go tool with the -race flag:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GY5JwzjEfgUW6JXRnUClOQ.png" /></figure><h4>Rust:</h4><p>Rust provides strong compile-time guarantees against data races. Its ownership and borrowing system ensures that the shared mutable state is accessed safely, making Rust a standout for concurrent programming safety.</p><p>Illustrating the borrow checker:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zCNWpebMT4FjTPsxmWIIvA.png" /></figure><p>In the Rust example above, after borrowing a slice of the vector, mutating the original vector would lead to a compile-time error.</p><h3>Conclusion:</h3><p>Both Go and Rust have their strengths when it comes to multithreading. Go’s goroutines and channels offer a more straightforward approach to concurrency, while Rust’s ownership system and threading primitives promise memory safety. The choice between them depends on the requirements of the task at hand and the developer’s preference for high-level abstractions versus low-level control.</p><p>Connect with me:</p><ul><li><a href="https://www.linkedin.com/in/muhammad-mavia-bba2811b6/">LinkedIn</a></li><li><a href="https://github.com/mauwia">GitHub</a></li><li><a href="https://twitter.com/maviadoteth_">Twitter</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b11c00a8ec0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>