<?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 Neda Divbandi on Medium]]></title>
        <description><![CDATA[Stories by Neda Divbandi on Medium]]></description>
        <link>https://medium.com/@neda_dvb?source=rss-dfca4f261218------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Nzibm_ojyngjzjAD9gh4lg.jpeg</url>
            <title>Stories by Neda Divbandi on Medium</title>
            <link>https://medium.com/@neda_dvb?source=rss-dfca4f261218------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 11:26:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@neda_dvb/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 Go GC Algorithm]]></title>
            <link>https://medium.com/@neda_dvb/understanding-go-gc-algorithm-c9001b7a8bf3?source=rss-dfca4f261218------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9001b7a8bf3</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[garbage-collection]]></category>
            <dc:creator><![CDATA[Neda Divbandi]]></dc:creator>
            <pubDate>Mon, 06 Jun 2022 15:09:57 GMT</pubDate>
            <atom:updated>2022-06-09T13:56:33.560Z</atom:updated>
            <content:encoded><![CDATA[<p>This article assumes that you are already familiar with the primary memory concept, heap vs stack. If not, please refer to my previous stories.</p><p>In short, a running program will store objects with two different approaches, the heaps and the stack. Garbage collection operates on the heap, not the stack.</p><blockquote>As of version 1.12, the Go programming language uses a non-generational concurrent tri-color mark and sweep collector. The implementation of Go’s collector has changed and evolved with every release of Go. So any post that talks about the implementation details will no longer be accurate once the next version of the language is released.</blockquote><p>Before jumping into the GC algorithm mechanism in Go, let’s clear that Go tries its best to keep objects on the stack, so most memory allocations will end up there. It is better to say that the compiler tries to determine a variable’s lifetime and size, If it succeeds, then it will be allocated to a stack frame. Stack frames are individual memory spaces for each function call, this means that Go has a stack per function, and when possible, Go will allocate variables to this stack.</p><p>Determining the variable lifetime is done by <strong>escape analysis, </strong>it<strong> </strong>chases across functions and packages to check if the memory should be allocated to a heap or stack.</p><p>To illustrate, consider the following:</p><pre>type sampleStruct struct {</pre><pre>text string</pre><pre>}</pre><pre>var newSampleStruct = sampleStruct{text: &quot;text&quot;}</pre><pre>func generateText(val1 string, val2 string) string {</pre><pre>return val1 + val2</pre><pre>}</pre><pre>func setSampleStruct() {</pre><pre>txt1:=&quot;text1&quot;</pre><pre>txt2:=&quot;text2&quot;</pre><pre>newSampleStruct.text = generateText(txt1,txt2)</pre><pre>}<br>func anyThingFunction() {</pre><pre>//some functionality</pre><pre>setSampleStruct()</pre><pre>}</pre><p>let’s analyze the code block :</p><p>newSampleStruct is a variable out of any scoop, so the compiler assigns it to the heap.</p><p>setSampleStruct will be allocated to the stack while the function is executing and the variables txt1 and txt2 which are obviously having known lifetime will be allocated to stack.</p><p>Once generateText is called, a new stack frame will be pushed into stack memory.</p><p>When execution ofgenerateText finishes, the result of the function is returned to anyThingFunction and the stack frame of generateText is popped off the stack cause we don&#39;t need it anymore.</p><p>The pointer to newSampleStruct is followed to the location on the heap containing it and the text field is updated.</p><p>anyThingFunction exits and the stack created for it is cleaned up. The value for newSampleStruct stays on the heap until garbage collection occurs and find out that there is garbage to collect ;)</p><h4>How does the GC work?</h4><p>The <strong>tri-color </strong>is the algorithm that Golang <strong>mark and sweep garbage collector</strong> uses, the algorithm is non-generational and <strong>concurrent</strong>.</p><p>As I previously mentioned, the Go compiler keeps trying to predict variable lifetime so it can leave heap alone and allocates stack which causes less usage of GC in general, so the generational algorithm which is based on the <a href="https://www.memorymanagement.org/glossary/g.html#term-generational-hypothesis">generational hypothesis</a> observation (<em>infant mortality) </em>is not too important to Go compiler, the object with known lifetime has already been allocated to stack, keep in mind that <em>infant mortality </em>assumes<em> </em>that newborn objects are more likely to die than older ones.</p><p>Garbage collectors have two key parts, a<strong> mutator, </strong>and a<strong> collector.</strong></p><p>As the name says, the <strong>collector</strong> is the section or functionality where the collecting and detecting of the garbage take place according to the underhood algorithm, and the <strong>mutator</strong> is the initial phase before any garbage collecting where the heap allocation happens.</p><h4>let&#39;s dig into the algorithm mechanism :</h4><p>I did mention the concurrent term, yes it is concurrent, which means that both mutator and collector run at the same time to keep it real.</p><p>From the name<strong> Mark and sweep </strong>we can easily guess how it works, the algorithm has two phases, marking and sweeping :) in the mark phase, the garbage will be detected in the heap, in the sweep phase, the garbage will be removed.</p><p>Don&#39;t get confused, they are not direct, it means that the mark does not mark the garbages , it will mark the non-garbages and the sweep will remove everything but not non-garbages.</p><h4>Implementation steps :</h4><p><strong>Stop the world (</strong>STW) is the crucial phase to check memory status, it actually mean stopping the running goroutines and turn write barrier on so that data on heap can be maintained.</p><p>Once all goroutines has the write barrier on , <strong>the world will be started ,</strong>and the workers will perform the garbage collection.</p><p>Like I already said, marking will use the tri-color algorithm,the algorithm divides objects in the heap into three sets according to the color assigned, black, white, and gray.</p><p>White objects are garbage. Grey ones need to be checked and figure out if they are still in use and have reference to the white ones. If they have, they will turn white. If not, then we have our black set which is guaranteed to not have any reference to the white set and they will stay safe.</p><p>The <strong>collector</strong> finds grey objects<strong> </strong>by traversing downwards from the roots objects,once that happend, the goroutine will be resumed and then new greyed object will be in a queue to turn black, then the world will stop again and the <strong>collector</strong> cleans up all the white nodes that are no longer needed.</p><h4>When to run the process ?</h4><p>Go has GOGC environment variable which is very old one , GOGC controls the aggressiveness of the garbage collector. Default value of this variable is100, increasing the value will postpone the GC running period , and decreasing will cause more often garbage collection, and obviously set to 0 will make it not run GC ever .</p><p>So the process will be triggered once the heap has grown by GOGC value% since the previous collection.</p><p>References :</p><p><a href="https://medium.com/safetycultureengineering/an-overview-of-memory-management-in-go-9a72ec7c76a8">An overview of memory management in Go</a></p><p><a href="https://dave.cheney.net/tag/gogc">https://dave.cheney.net/tag/gogc</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9001b7a8bf3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Python GC Algorithms]]></title>
            <link>https://medium.com/@neda_dvb/understanding-python-gc-algorithms-4c4ddbe53ffb?source=rss-dfca4f261218------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c4ddbe53ffb</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[garbage-collection]]></category>
            <dc:creator><![CDATA[Neda Divbandi]]></dc:creator>
            <pubDate>Sun, 29 May 2022 13:06:17 GMT</pubDate>
            <atom:updated>2022-05-30T08:01:04.334Z</atom:updated>
            <content:encoded><![CDATA[<p>Python has two garbage-collection algorithms: one which works with the reference count ,the other is the cycle-detecting (Generational Garbage Collection)algorithm.</p><p>In Python, everything is an object, which means every entity has some metadata (attributes) and associated functionality (methods), so, we can say that even an integer is an object.</p><p>Python objects have three meta data: type, value, and reference count.</p><h3>Reference counting algorithm:</h3><p>Reference counting is a programming technique of storing the number of references, pointers, or handles to a resource, such as an object, a block of memory, disk space, and others.</p><p>In Python, all objects and data structures are stored in the private heap and are managed by Python Memory Manager internally.</p><p>Reference counting is the simplest garbage collection algorithm.</p><p>The algorithm simply looks for the object with zero references , or counts the number of pointer references to each allocated object.</p><p>In this algorithm, garbage is identified by having a reference count of zero.</p><h4>How does it work?</h4><p>Variables in Python are just references to the objects in the memory.</p><p>Lets check this out</p><p>a=1</p><p>b=a</p><p>c=1</p><p>As every variable in Python is a reference (a pointer) to an object and not the actual value itself, the assignment statement just adds a new reference to the object <em>integer 1</em>. Therefore, the object is the same, the reference count increases by 1! Because every object has its own ID, if we print the IDs of objects, we see the same result for all of them. That means that the reference count of integer object 1 is 3 .</p><p>Now, let’s modify the object and see the result.</p><p>a=None</p><p>Still, we have two references to the object <em>integer 1</em>. If we continue to change the value of the variables <strong>b</strong> and <strong>c </strong>we reach to the point where the object has no reference , or reference count of 0 , then we have a garbage to remove and free the memory.</p><h4><strong>Disadvantages:</strong></h4><p>The most important issue in reference counting garbage collection is that it doesn’t work in cyclical references.</p><p>A=[]</p><p>a.append(a)</p><p>Tada!!! We have a list of objects which never have 0 references. Each object in the list has reference to another one. A solution ? cycle-detecting algorithm :D</p><h3>A cycle-detecting algorithm (circular references)</h3><p>This algorithm discovers and destroys circular references. Circular references occur when one or more objects are referencing each other. Like appending objects to a list.</p><p>lets consider previous example :</p><p>list=[]</p><p>list.append(list)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*4Hz4Yfcvr3Yfy4saWwGQlA.jpeg" /></figure><p>The list object points to itself , and object1 and object2 point to each other , so the reference count of the object never reaches to 0. Therefore, the reference counting algorithm doesn’t work here.</p><p>Generational garbage collection is a type of trace-based garbage collection. It can break cyclic references and delete unused objects <em>in that generation and all its younger generations</em><strong>, </strong>even if they are referred by themselves.</p><h4>How does it work?</h4><p>Python keeps track of every object in memory. 3 lists are created when a program is run. Generation 0, 1, and 2 lists.</p><p>Newly created objects are put in the Generation 0 list. A list is created for objects to discard. Reference cycles are detected. If an object has no outside references, it is discarded. The objects who survived after this process are put in the Generation 1 list. The same steps are applied to the Generation 1 list. Surveillance from the Generation 1 list is put in the Generation 2 list. The objects in the Generation 2 list stay there until the end of the program execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*o71rRxdCmdsiPEL43z7Akw.jpeg" /></figure><h3>Conclusion:</h3><p>Python supports automatic garbage collection, which is very useful for developers and prevents memory leaks. It has two garbage-collection algorithms: one for dealing with the reference count, which, when the reference count is zero, frees allocated memory. The other is the cycle-detecting algorithm, which discovers and destroys generational references. Although it is an automated action, it can be useful to understand what is happening under the hood.</p><p>Reference <a href="https://towardsdatascience.com/memory-management-and-garbage-collection-in-python-c1cb51d1612c">https://towardsdatascience.com/memory-management-and-garbage-collection-in-python-c1cb51d1612c</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c4ddbe53ffb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic concepts of garbage collector]]></title>
            <link>https://medium.com/@neda_dvb/basic-concepts-of-garbage-collector-42e960e6ab49?source=rss-dfca4f261218------2</link>
            <guid isPermaLink="false">https://medium.com/p/42e960e6ab49</guid>
            <category><![CDATA[garbage-collection]]></category>
            <dc:creator><![CDATA[Neda Divbandi]]></dc:creator>
            <pubDate>Sat, 21 May 2022 16:48:17 GMT</pubDate>
            <atom:updated>2022-05-21T17:00:13.988Z</atom:updated>
            <content:encoded><![CDATA[<p>Automatic managing and allocating memory is one of the key concepts of software engineering which is called garbage collection .</p><p>It refers to automatic management of memory by freeing unused heap memory buckets. Why heap? It’s because the stack is last in first out, so there is no need to collect garbage. With the stack, as soon as a function returns, we can be confident (excepting programmer error) that the local variables aren’t being used anymore, so they are deallocated automatically at that time in nearly every language.</p><p>As we know, RAM is not infinite , garbage is referred to unreachable memory (memory with no reference but has value) or imagine there is an object stored in a memory but is not going to be used any more, so if we don’t collect it we will run out of memory and we have no where to store data any more. GC is one of the most common memory management in modern languages and the process often runs at certain intervals.</p><p>History :</p><p>Garbage collection was invented by American computer scientist John McCarthy around 1959 to simplify manual memory management in Lisp language,(Developed in 1959 by John McCarthy) Lisp language is sometimes called the twin sister of GC technology. It was the first language which was highly dependent on GC .</p><p>In fact, John McCarthy, invented garbage collection to simplify programming in Lisp . So, historically, the two are tied together.</p><p>J. McCarthy is known as the father of Lisp. He invented the lisp language and completely described the garbage collection for the first time.</p><p>Advantages of GC</p><p>Automatic deallocation allows a programmer not to worry about memory management , increasing writeability of a system, and decreasing development time and costs.</p><p>Garbage collection promotes purely modular design .</p><p>Many programmers argue that automatic garbage collection is inefficient compared to explicit storage reclamation. However, several studies showed that the performance of systems with well-implemented garbage collectors is highly competitive with systems with explicit deallocation.</p><p>Disadvantages of GC</p><p>explicit deallocation causes one module to be responsible for knowing that other modules are not interested in this particular object.</p><p>Garbage collection is a language requirement for functional languages, which cannot use a stack-based environment because of unpredictable execution patterns.</p><p>Each programming language implements GC differently, but they are similar in that the process occurs automatically behind the scenes.</p><p>Here are some classic algorithms :</p><ul><li><a href="https://rebelsky.cs.grinnell.edu/Courses/CS302/99S/Presentations/GC/#reference">Reference Counting</a></li><li><a href="https://rebelsky.cs.grinnell.edu/Courses/CS302/99S/Presentations/GC/#marksweep">Mark-Sweep</a></li><li><a href="https://rebelsky.cs.grinnell.edu/Courses/CS302/99S/Presentations/GC/#markcompact">Mark-Compact</a></li><li><a href="https://rebelsky.cs.grinnell.edu/Courses/CS302/99S/Presentations/GC/#copying">Copying Collection</a></li><li><a href="https://rebelsky.cs.grinnell.edu/Courses/CS302/99S/Presentations/GC/#noncopying">Non-Copying implicit collection</a></li></ul><p>some more creative ones are as below:</p><ul><li><a href="https://rebelsky.cs.grinnell.edu/Courses/CS302/99S/Presentations/GC/#incremental">Incremental Tracing Collection</a></li><li><a href="https://rebelsky.cs.grinnell.edu/Courses/CS302/99S/Presentations/GC/#generational">Generational Collection</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42e960e6ab49" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic Concepts Of Memory Allocation]]></title>
            <link>https://medium.com/@neda_dvb/basic-concepts-of-memory-allocation-a70f620d0229?source=rss-dfca4f261218------2</link>
            <guid isPermaLink="false">https://medium.com/p/a70f620d0229</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[heap-memory]]></category>
            <dc:creator><![CDATA[Neda Divbandi]]></dc:creator>
            <pubDate>Sat, 16 Apr 2022 10:47:56 GMT</pubDate>
            <atom:updated>2022-04-17T19:40:58.048Z</atom:updated>
            <content:encoded><![CDATA[<p>Memory is the most essential element of a computing system, generally speaking. Computer memory is of two basic types — Primary memory (RAM and ROM) and Secondary memory (hard drive, CD, etc.).</p><p>In this paper, I will discuss primary memory.</p><p>Memory can be called as a sequential set of “buckets” which are laid out in sequential order from 0 on up (one byte at a time) that can contain various data types (numbers, characters, boolean etc.).</p><p>Each bucket in memory has a unique identifier which is called address, which is used for tracking where information is stored, mostly by the CPU via data buses , they carry memory addresses from the processor to other components.</p><p>Accessing to the memory addresses can be very useful in computing,Imagine you want to sell your bike, it’s much easier to send picture of your bike but not the real bike to a buyer, in that case if the buyer just have the picture (address) he/she make decision whether buy it or not, imagine if you have 100 of the same bike (multiple variable with same values), you can use the same image (address) and get the same value for 100 of other buyers.</p><p>In some programming languages you can easily access the variable address, which reduces the size of the value being sent, or returned by a method.</p><p>A small example in C might give you better context, in this example we don’t care about value of variable <em>a</em>, we need to find out where <em>a</em> is located:</p><p>#include &lt;stdio.h&gt;<br>int main()<br>{<br>int a= 55;<br>printf(“The address of a is %p”, &amp;a);<br>return 0;<br>}</p><p>the result will be like this:</p><pre>The address of a is 0x7ffc0ecd095c</pre><p>`0x7ffc0ecd095c` is the exact address of a memory block where a located.</p><p>This action is done with pointer, generally saying, a pointer is a variable whose value is the address of another variable.</p><p>Base on the above examples, accessing to the memory addresses helps compiler (or interpreter) associates variables, but the question is how?</p><p>For better understanding, we need to level up our knowledge about heap and stack.</p><blockquote><em>Heap and stack are both</em> memory allocation mechanism where some of processor’s registers information gets saved, information such as which functions are called, what variables you created etc. Keep in mind that they both are generic terms which are used to describe how allocation operations take place. They can be implemented in many ways, and the terms apply to the basic concepts. As I previously mentioned memory can contain different data types, and data types are key topic in understanding how heap and stack difference from one another, therefore we need to know a bit about data types as well.</blockquote><h3>Data types:</h3><p>Generally, data types can divide into two main categories :</p><p><em>Value types and reference types,</em> they both can have predefined types and user-defined types. The differentiation between value type and reference type depends on two features, which are where the variables are stored in memory and how they behave with an assignment statement.</p><p>In fact value of the value type is the actual value, but a value of reference type is a <a href="https://en.wikipedia.org/wiki/Reference_(computer_science)">r</a>eference to another value, or better to say like this, a value type holds a data value within its own memory space while a reference type holds a pointer to another memory location that holds the data.</p><p>Here is some key Difference Between Value Type and Reference Type:</p><h4>Data Types Assignment</h4><blockquote>In value type, the value is copied to the new location, so there are two identical copies of the same value in the memory.</blockquote><blockquote>In reference type, the reference is copied while the actual value remains the same</blockquote><h4>Examples</h4><blockquote>The int, float, double, enum are some examples of value types. Pointers, slices , maps, functions, and channels are some examples of reference types in <a href="https://go.dev/">Golang</a>.</blockquote><blockquote>Now that we have basic understanding regarding data types, we can continue with heap and stack.</blockquote><h3>Stack :</h3><p>Don’t confuse it with stack data structure, they have similar names, stack memory behaves like a stack data structure. That is why it’s called stack.</p><p>As I said, the allocation mechanism is the keyword in understanding differences between heap and stack. In stack, memory is allocated in a contiguous block, so that the compiler is aware of the size of memory to be allocated. We call it a stack memory allocation because the allocation happens in the function call stack. Once the function call is done, the allocated memory will be free (memory de-allocation) and data belongs to that method flushes out from the stack. Therefore, we can agree that this type of allocation is temporary and value type data which are usually created by a function are stored in a stack. In stack, variables are declared, stored and initialized during run-time also access to them is very fast. Stack is always reserved in a LIFO (last in, first out).</p><p>This mechanism is very simple and typically much faster than heap-based memory. It’s also considered safer allocation as compared to heap memory allocation because the data stored can only be accessed by owner thread and, the last point is it has less storage space as compared to heap-memory. For conclusion, we can say stack is a run-time storage management technique which mostly includes methods, local variables, and reference variables.</p><h3>Heap :</h3><p>Don’t confuse it with heap data structure. It is called heap because it is a pile of memory spaces available to allocate and de-allocate</p><p>In heap which is also known as dynamic memory allocation ,memory is allocated in random order. It means that there is no particular order to the way items are placed, so there is a pile of memory space available for programmers to allocate and de-allocate . Every time an object is initialized ,it is always created in Heap-space and the referencing information to these objects is always stored in Stack-memory. In the heap mechanism, an automatic de-allocation feature is not provided. We always need garbage collectors to remove old unused objects in order to use the memory efficiently. Some of the disadvantages are as followed :</p><ul><li>The access of this technique is slow compared with stack</li><li>The size of heap is quite big compared to the Stack-memory</li></ul><h3><strong>memory allocation</strong> :</h3><p>We call it memory allocation since the term management is generally used for OS , and various memory allocation refers more to computer programs and services.</p><p>Generally speaking, we have two main types of memory allocations , static and dynamic. Yeah, now you got it. Why do we need to know about heap and stack. These are our key words .</p><p><strong>Static memory allocation:</strong></p><p>Stack is used for static allocation.The program is allocated memory at compile time since we know exactly how much memory we need to allocate . In this technique we have a fixed amount of memory to allocate, which is done during compiling. Global variables are a good example of this type of allocation. The allocated memory can not increase or decrease after allocation, so the exact size should be known in advance. The static memory is not reusable during run time . At some point the allocated memory needs to be released, otherwise in some cases, we might face memory leakage the reason is that program consumes memory but is unable to release.</p><p><strong>Dynamic memory allocation :</strong></p><p>heap is used for that purpose. It means that the memory assignment happened during program run time. As you can guess, unlike static allocation, we don’t know how much space we need to allocate in advance or before run time. This technique can be used when you have data structures without any upper limit of memory space.</p><p>Now imagine if we have big amount of objects which are being created on heap and the memory of them is allocated dynamically , imagine for some reasons we don’t have access to the reference of them , reference-less objects are unreachable , they will stay there forever and as RAM is not infinite there we go , we will have a disaster which is called <a href="https://en.wikipedia.org/wiki/Memory_leak">memory leak </a>, where unused objects occupy unnecessary space in memory , and if no one collect them very soon we will be out of space to store new objects , but we have a savor for that which is called Garbage collector, that guy will collect those dead objects , and the freed memory buckets will be usable again .</p><blockquote>More optimized GC algorithm less memory leakage</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a70f620d0229" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>