<?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 Muhammad J. Gholami on Medium]]></title>
        <description><![CDATA[Stories by Muhammad J. Gholami on Medium]]></description>
        <link>https://medium.com/@muhammadjgholami?source=rss-a158862d4d9c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*u1y1MNC6gkdjbIsI</url>
            <title>Stories by Muhammad J. Gholami on Medium</title>
            <link>https://medium.com/@muhammadjgholami?source=rss-a158862d4d9c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 18:10:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@muhammadjgholami/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[Comparing Golang and C# GC Algorithms]]></title>
            <link>https://muhammadjgholami.medium.com/comparing-golang-and-c-gc-algorithms-1c5721c6e006?source=rss-a158862d4d9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c5721c6e006</guid>
            <dc:creator><![CDATA[Muhammad J. Gholami]]></dc:creator>
            <pubDate>Mon, 11 Mar 2024 07:14:44 GMT</pubDate>
            <atom:updated>2024-03-11T07:14:44.423Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jZQmIKwwYTW48h8A" /><figcaption>Photo by <a href="https://unsplash.com/@gary_at_unsplash?utm_source=medium&amp;utm_medium=referral">Gary Chan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this blog post series, we will discuss the GC aspects that we should consider when choosing a GC algorithm, the memory management algorithms utilized by Golang and C#, and also compare them to gain a better understanding of their respective use cases.</p><p>Although I’m not a memory guy, I attempted to write my research on this cool competition. This will help us to gain a better understanding of the nature of these two languages. As it might become a long blog, I’ve decided to divide it into multiple parts. In the first part, we’ll discuss basic algorithms that both languages are using and in the next parts, we’ll delve into actual comparison details. So if you’re already familiar with this content, feel free to skip ahead. But if you’re interested, grab a seat and a cup of coffee, because it gonna be so much theory.</p><h3>Let’s travel the history</h3><p>Managing memory is one of the most challenging aspects of computer science, It involves handling virtual spaces, the stack, heap, and more. Every program, regardless of the programming language used, has to deal with these memory spaces.</p><p>At the very first, during assembly time, programmers had to control everything, even down to managing the stack. I’m reading from your face that, it’s not so cool, so the desire for a more automated approach led to the creation of the C programming language. After all, we’re all seeking a more automated world.</p><p>With the introduction of C, things improved significantly. The heap, Code Segment, Data Segment, BSS, etc. Also, the stack was automatically handled, bringing satisfaction to everyone involved. The only remaining challenge was the management of dynamic memory or the heap.</p><p>This gave rise to the concept of Garbage Collection (GC), another idea to automatically handle something. But, of course, it comes with its challenges and lots of algorithms to solve them. In my opinion, as a rule of thumb, every time an automated idea is conceived, it results in numerous solutions aimed at overcoming its challenges.</p><p>These days there are numerous programming languages and each one of them chooses the GC algorithm that they think is best for their purposes. Golang chose a tricolor, mark-and-sweep, concurrent algorithm which resulted in lower paused time but more program throughput. Make it useful for systems that require real-time services like trading applications or system-level programs like docker. On the other hand, C# uses a combination of mark-and-sweep and mark-and-compact with a generational collector, which results in higher pause times but more application throughput. In this blog post, I will write about GC aspects that we should consider when choosing a GC algorithm, and also compare the GC algorithm of two programming languages, Golang and C#.</p><h3>Key Factors to Consider</h3><p>Here are different factors that we should consider when choosing a GC algorithm.</p><h4>Safety</h4><p>The most important thing is that garbage collectors must not collect live objects and they must be safe. However, everything comes with a cost, the cost of being safe particularly affects concurrent collectors (more on this later). But we do have some algorithms like old-fashioned mark/sweep that will stop the whole application while executing both mutator and collection to provide safety</p><h4>Throughput</h4><blockquote><em>The primary goal of automation is to make an ease for their client, as a programming language designer you wanna make your clients (programmer) to only write their application logic, the hard part of managing stuff is on your shoulders</em></blockquote><p>The cost of all GC algorithms is the tracking process. usually, this tracking process is a dedicated code logic that needs to be run to track garbage. It’s called the mutator, The issue is how much the algorithm slows the actual program down. Some algorithm tunes this factor by trading some collector performance (pause time) for increased mutator throughput.</p><h4>Completeness</h4><p>Ideally, garbage collection should be complete: eventually, all garbage in the heap should be reclaimed. However, this is not always possible or even desirable. Some algorithms like generational collectors play with this factor to gain other benefits like reducing the average pause time</p><h4>Pause Time</h4><p>GC algorithms have to stop the whole application to execute collection safely this behavior is named stop-the-world. The question is how often and how much does your collector stop the world? Some algorithms provide concurrent collection and claim they do not pause the application execution frequently and do this task in the background but the cost is increasing throughput.</p><h4>Space overhead</h4><p>The goal of memory management is the safe and efficient use of space. Different memory managers, both explicit and automatic, impose different space overheads. Almost all algorithms use additional memory like object headers to track objects’ lifetime.</p><h4>Scalability</h4><p>The final metrics we identify here are scalability and portability. With the prevalence of multicore hardware on desktops, laptops, and even portable devices such as tablets and mobile phones (rather than just in large servers), it is becoming increasingly important that garbage collection can take advantage of the parallel hardware on offer. Furthermore, parallel hardware is increasing in scale (number of cores and sockets) and heterogeneous processors have become common. The demands on servers are also increasing, as heap sizes move into the hundreds of gigabytes or even terabytes and as transaction loads increase. Some collection algorithms depend on support from the operating system or hardware (for instance, by protecting pages or by double mapping virtual memory space, or on the availability of certain atomic operations on the processor). Such techniques are not necessarily portable.</p><h4>Warmup Time</h4><p>Does your algorithm self-adjust based on measured behavior and if so, how long does it take to become optimal?</p><h4>Page Release</h4><p>Does your algorithm ever release unused memory back to the OS? If so, when?</p><h3>Mark-sweep Algorithm</h3><p>The mark-sweep algorithm is very simple. If a thread is unable to allocate a new object, the collector is called and the allocation request is retried. If there is still insufficient memory available to meet the allocation request, then a fatal error or an exception going to be thrown. while the collection process all threads must be stopped and in some scenarios for the marking process all threads should be stopped too.</p><p>The mark-sweep algorithm is a tracing garbage collector, which means it traces all objects directly or indirectly accessible by the program. It follows a simple two-phase process: tracking and identifying all unused objects, followed by deleting them.</p><h4>Mark Phase</h4><p>In this phase, the algorithm identifies all live objects and sets their “marked” bit to true, either in the object’s header or in a side table. If you put the mark bit in the object header, you have put it next to the object itself, and it’s beneficial because it improves cache locality. The objects that are marked recently are the ones we’ll deal with next and hence are likely to still be in the hardware cache.</p><p>On the other hand Side Table is a separate data structure that has its own dedicated memory space. This offers us more flexibility, especially in scenarios where the object size is highly variable or the “marked” bit needs to be dynamically resized based on specific conditions. However, it also adds complexity to the garbage collection process.</p><p>For a single-threaded environment, this side table could be implemented as a stack. This leads to a depth-first traversal of the graph. For a multi-thread environment, one solution is to have a side table (or work list) for each thread. It may be preferable to swiftly scan the roots of each thread, for example, a concurrent collector might briefly pause each thread to scan its stack and then traverse the graph while the mutator is running.</p><h4>Sweep Phase</h4><p>Clear memory for all the unreachable (garbage) objects whose marked bit is false. Objects with a marked bit set to <strong>true</strong> are left untouched because they are still reachable.</p><p>The sweep phase returns unmarked nodes to the allocator. Typically, the collector sweeps the heap linearly, starting from the bottom, freeing unmarked nodes and resetting the mark bits of marked nodes in preparation for the next collection cycle.</p><p>Keep in mind that the mark-sweep collector imposes constraints upon the heap layout. First, this collector does not move objects. The memory manager must therefore be careful to try to reduce the chance that the heap becomes so fragmented that the allocator finds it difficult to meet new requests. Which would lead to the collector being called too frequently, or in the worst case, preventing the allocation of new memory at all. Second, the sweeper must be able to find each node in the heap. In practice, given a node, the sweep must be able to find the next node even in the presence of padding introduced between objects to observe alignment requirements.</p><p>Mark-sweep in comparison to other GC algorithms imposes no overhead on mutator read and write operations. However, it is commonly used as a based algorithm for more complex collectors like generational, concurrent, and incremental algorithms. All these algorithms require the mutator to inform the collector when they modify pointers. However, the overhead of doing so is typically small.</p><p>Mark-sweep garbage collection uses less memory than other techniques since it does not move or copy objects, it only needs to set a bit or byte for each live object discovered and identify the roots of the collection, Both of these considerations may be important in environments where memory is tight or where the run-time system cannot provide type-accurate identification of references. The pause time for collection depends on the program being run and its input, but can easily extend to several seconds or worse for large systems.</p><p>However, Being a non-moving collector, mark-sweep is vulnerable to fragmentation. If the application does not allocate many large objects and object sizes do not change much, we could use an allocation strategy like segregated fits to mitigate fragmentation concerns, but it could be a big problem in long-running applications. For this reason, most production Java virtual machines and also .NET use moving collectors that can compact the heap.</p><h3>Mark-and-Compact Algorithm</h3><p>Fragmentation can be a problem for non-moving collectors. Even if there’s space available in the heap, there might not be a big enough continuous area of free space for a new allocation. This can slow down the process because the memory manager has to hunt for suitable free space.</p><p>To tackle this issue, allocators can group small objects of the same size in blocks, this works well when there aren’t many big objects and the sizes of objects stay mostly the same. However, in long-running applications managed by non-moving collectors, heap fragmentation can occur over time, leading to performance issues.</p><p>The solution for this is moving collectors like Mark-compact algorithms. They work through several phases. The initial phase is always marking, to identify which objects are still in use. Afterward, further compacting phase, the heap often becomes fragmented, with gaps between live objects. The goal of the compact phase is to relocate the live objects in memory so that they are contiguous and eliminate fragmentation. However, the challenge lies in updating pointers to the moved objects, as their memory addresses change during compaction. Any moving collector can rearrange heap objects in one of three ways.</p><ul><li><strong>Arbitrary:</strong> Objects are moved without considering their original position or their connections to other objects.</li><li><strong>Linearizing:</strong> Objects are shifted next to related objects whenever feasible. This includes objects referring to each other, being siblings in a data structure, etc.</li><li><strong>Sliding:</strong> Objects are shifted to one end of the heap, pushing out garbage, while keeping their original order intact.</li></ul><p>Most compacting collectors use either arbitrary or sliding orders. Arbitrary order compactors are simple to make and run fast, especially when all nodes are the same size. However, they can mess up the order of objects and negatively impact the mutator because related objects might end up scattered across different cache lines or virtual memory pages.</p><p>Almost all modern mark-compact collectors use sliding compaction. This keeps the objects in the same order, so the mutator can find them easily. Some algorithms like copying collectors can even improve how efficiently the mutator works by placing the objects close to their parents or siblings.</p><p>Although Mark-compact solves the fragmentation issue, but there is, of course, a price to be paid. Mark-compact collection is likely to be slower than mark-sweep because it incurs additional overheads on the mutator. Consequently, it results in worse throughput than mark-sweep, mainly due to making more passes over objects in the heap. A common solution is to run with mark-sweep collection for as long as possible, switching to mark-compact collection only when fragmentation metrics suggest that it would be beneficial.</p><p>In moving collectors like copying collectors, long-lived or even immortal data tends to accumulate near the beginning of the heap and gets repeatedly copied, which can be inefficient. Generational collectors handle this better by moving such data to a separate space that is only cleaned infrequently. However, this approach may not be suitable if there’s limited heap space or if the data being collected is in the oldest generation of a generational collector. Mark-compact collectors offer a solution by allowing objects in this long-lived or immortal “sediment” area to remain uncompacted, avoiding unnecessary copying or movement.</p><h3>Generational Collector</h3><p>The goal of a collector is to reclaim the space occupied by dead objects. Every collection algorithm has its advantages, for example, the Tracing collectors are most efficient if the space they manage contains few live objects. On the other hand, long-lived objects are handled poorly if the collector processes them repeatedly, either marking and sweeping or copying them again and again. So why we do not use multiple algorithms in one system?</p><p>Generational collectors address this challenge by organizing objects into generations based on their age, typically segregating them into physically distinct areas of the heap. There are usually at least two generations: one for young objects and another for older ones. The young generation is where newly created objects are placed, while the old generation houses objects that have survived long enough in the young generation. Each generation can be collected and traced using different algorithms. In C#, Gen 0 primarily uses a combination of mark-sweep and copy, while Gen 1 and 2 use mark-compact collection Another significant advantage of generational collectors is the ability to control collection times by adjusting the size of each generation, allowing for more predictable pause times during collection processes.</p><p>However, despite these benefits, there are scenarios where a generational collector needs to collect the entire heap. This typically occurs when the allocator runs out of space, and the collector predicts that collecting only younger generations won’t free up sufficient space. While generational collection improves expected pause times, it doesn’t address worst-case scenarios, making it inadequate for real-time systems without additional mechanisms.</p><p>Generational collection can also improve throughput by avoiding repeatedly processing long-lived objects. But there are some downsides. If something lasts a long time and then becomes garbage, it might take a while before it’s cleaned up. This delay happens because the system typically focuses on cleaning up newer, short-lived objects first. Only when it’s necessary does it look at older, long-lived objects. Here I write a bullet list of advantages and disadvantages of generational collectors.</p><ul><li>Generational collections give us the power of tuning, by perfectly doing it, we can meet throughput and pause-time simultaneously.</li><li>There is a hypothesis that states that most objects have a short lifespan. In other words, newly created objects tend to be garbage collected quickly. Conversely, objects that survive multiple garbage collection cycles tend to live longer</li><li>The primary goals of generational garbage collection are to reduce pause times and improve throughput. and expected pause times depend largely on the volume of data that survives a minor collection of the youngest generation, which is influenced by the size of the generation. If the size of the youngest generation is too small, the collection will be fast but little memory will be reclaimed, leading to several undesirable consequences.</li><li>Young-generation collections will be too frequent, incurring costs related to copying objects and stopping threads.</li><li>The older generation will fill up too quickly, and then it too needs to be collected, necessitating more frequent and time-consuming full heap collections.</li><li>If these young objects are promoted too early, their high mutation rate will put further pressure on the mutator’s write barrier.</li><li>Ability to use different algorithms in different generations, you can even play with generations, the generational algorithm needs at least two generations but you can add more generations to it.</li><li>Adding further generations makes balancing short pause times for young-generation collections without causing too many full heap collections due to the oldest generation filling up too quickly.</li><li>collecting intermediate generations takes longer than younger generation collections, although less time than full heap collections.</li><li>Increasing the number of generations may create more intergenerational pointers, potentially increasing pressure on the mutator’s write barrier.</li><li>Generational collection improves expected pause times but doesn’t solve the problem of worst-case pause times, especially for large heaps.</li><li>Generational collection alone can’t guarantee meeting deadlines in hard real-time systems.</li></ul><h3>Concurrent GC</h3><p>Concurrent algorithms are without a doubt more complex to design than stop-the-world collectors. A concurrent collector is a type of garbage collector that performs most of its work while the application threads are running, without stopping them frequently or for long periods. This reduces the pause times and improves the responsiveness of the application. But this typically comes at the cost of significant overhead on both the mutator and the collector. To limit the pauses caused by concurrent GC, the collector must also be on the fly. This means that the collector does not stop all the mutators at once, but only one at a time, and only for a short period. This way, the collector can access the roots of the mutators, which are the references to the objects that they use.</p><p>Generational collector, on the other hand, can offer expected pause times for most applications of only a few milliseconds. However, their worst case (a full heap collection) may pause an application for very much longer, depending on the size of the heap, the volume of live objects, and so on. Such delays may not be acceptable.</p><p>However, there are advantages, and disadvantages to concurrent collection specifically the concurrent mark-and-sweep algorithm that Golang uses, here are some of them:</p><ul><li>It does not move or compact the live objects, which means that the memory can become fragmented over time. Fragmentation is when there are small gaps between the allocated memory blocks, which can reduce the available space and slow down the allocation process.</li><li>It may not be able to finish the collection before the memory is full, which leads to a concurrent mode failure. This is when the collector has to stop the program and complete the collection in a stop-the-world manner, which can cause long pauses.</li><li>It requires more processor resources than a stop-the-world collector, which can affect the performance of the program.</li><li>mark-sweep collectors make better utilisa­tion of space than copying collectors since they do not require a copy reserve</li><li>non-moving concurrent collectors have a further advantage over other concurrent collec­tors: a simpler heap coherency model. All concurrent collectors require mutators to inform the collector of changes to the topology of the heap to prevent a mutator from hid­ing objects from a collector. In addition, collectors that move objects must ensure that only one collector thread moves an evacuated object and that it appears to mutators that all references to a moved object are updated atomically.</li></ul><h3>Final thought</h3><p>While I’ve focused on specific garbage collection algorithms in this blog, it’s important to note that numerous other fundamental algorithms exist like Copying GC and Reference Counting. I’ve omitted their discussion here since they aren’t utilized in languages such as Golang or C#. Nevertheless, these basic algorithms serve as building blocks for more intricate approaches employed by modern programming languages.</p><p>In the next blog post, I’ll delve deeper into the actual comparison of GC algorithms chosen by both languages. I’ll discuss the language’s use cases based on memory usage and the performance that they offer. Feel free to leave comments or reach out to me if you have any questions or ideas to make this blog better. Stay tuned.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c5721c6e006" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>