{"id":196799,"date":"2021-03-08T16:00:54","date_gmt":"2021-03-08T13:00:54","guid":{"rendered":"https:\/\/en.buradabiliyorum.com\/what-is-garbage-collection-and-how-does-it-affect-your-programs-performance-cloudsavvy-it\/"},"modified":"2021-03-08T16:00:54","modified_gmt":"2021-03-08T13:00:54","slug":"what-is-garbage-collection-and-how-does-it-affect-your-programs-performance-cloudsavvy-it","status":"publish","type":"post","link":"https:\/\/buradabiliyorum.com\/en\/what-is-garbage-collection-and-how-does-it-affect-your-programs-performance-cloudsavvy-it\/","title":{"rendered":"#What Is Garbage Collection, and How Does It Affect Your Program\u2019s Performance? \u2013 CloudSavvy IT"},"content":{"rendered":"<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_84 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<label for=\"ez-toc-cssicon-toggle-item-6a2da9bfe7963\" class=\"ez-toc-cssicon-toggle-label\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #dd3333;color:#dd3333\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #dd3333;color:#dd3333\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/label><input type=\"checkbox\"  id=\"ez-toc-cssicon-toggle-item-6a2da9bfe7963\" checked aria-label=\"Toggle\" \/><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/buradabiliyorum.com\/en\/what-is-garbage-collection-and-how-does-it-affect-your-programs-performance-cloudsavvy-it\/#Stack_vs_Heap\" >Stack vs. Heap<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/buradabiliyorum.com\/en\/what-is-garbage-collection-and-how-does-it-affect-your-programs-performance-cloudsavvy-it\/#Cleaning_Up_Your_Garbage\" >Cleaning Up Your Garbage<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/buradabiliyorum.com\/en\/what-is-garbage-collection-and-how-does-it-affect-your-programs-performance-cloudsavvy-it\/#Impacts_On_Performance\" >Impacts On Performance<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/buradabiliyorum.com\/en\/what-is-garbage-collection-and-how-does-it-affect-your-programs-performance-cloudsavvy-it\/#How_To_Speed_Up_Performance\" >How To Speed Up Performance?<\/a><\/li><\/ul><\/nav><\/div>\n<p><strong>&#8220;#What Is Garbage Collection, and How Does It Affect Your Program\u2019s Performance? \u2013 CloudSavvy IT&#8221;<\/strong><\/p>\n<div id=\"article-content-area\">\n<figure style=\"width: 700px\" class=\"wp-caption alignnone\"><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-10035 size-full\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/c42d50c4814e817d1516b7b42dd45a8a\/p\/uploads\/2021\/03\/5f73f353.png\" alt=\"\" width=\"700\" height=\"350\" data-crediturl=\"https:\/\/www.shutterstock.com\/image-photo\/office-garbage-near-metal-basket-337482248\" data-credittext=\"Shutterstock\/Smit\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><figcaption class=\"wp-caption-text\"><span class=\"imagecredit\"><a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/www.shutterstock.com\/image-photo\/office-garbage-near-metal-basket-337482248\">Shutterstock\/Smit<\/a><\/span><\/figcaption><\/figure>\n<p>Garbage collection is a feature of many languages like C# and Java. While manual memory management like C++ can be quite fast, automatic garbage collection improves the quality-of-life for developers. However, it\u2019s important to understand the performance implications of leaving GC to do your job.<\/p>\n<h2 role=\"heading\" aria-level=\"2\"><span class=\"ez-toc-section\" id=\"Stack_vs_Heap\"><\/span>Stack vs. Heap<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>To understand what a garbage collector does, you first need to understand the difference between memory stored on the stack, and memory stored on the heap. Both are specific memory locations in the memory assigned to your program, from your computer\u2019s available RAM.<\/p>\n<p>The <strong>Stack<\/strong> is fast, and is used for value types that have a fixed byte size. It\u2019s the same physical memory as the heap of course, it\u2019s just fast because it\u2019s a very orderly First-In, Last-Out data structure. Whenever you make a local variable, it stores it on the stack, and whenever your function exits and the variable goes out of scope, it is automatically cleaned off the stack.<\/p>\n<p>This is a very quick process and makes stack allocations basically free. Though there is a performance penalty, it\u2019s as cheap as it\u2019s gonna get.<\/p>\n<p>The <strong>Heap,<\/strong> on the other hand, is used for large objects like lists and strings that are too big to be stored on the stack, or need to be stored long after functions go out of scope, which stack allocations can\u2019t do by design. Whenever you do <code>new object<\/code>, you\u2019re making a heap allocation. You\u2019re also probably making a stack allocation, since if you\u2019re storing a reference into a local variable, that local variable must be created to point to the actual memory of the new object.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"imgchk9 alignnone wp-image-6013 size-full\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/2c70adc24fdee57fb49e0f8591f639cc\/p\/uploads\/2020\/08\/86ab1003.png\" alt=\"Heap allocations are also slower than stack allocations.\" width=\"700\" height=\"321\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>The heap is quite a bit slower, both to allocate memory onto, and remove from. This <a href=\"https:\/\/buradabiliyorum.com\/en\/category\/download-scripts-themes-apps\/\" data-internallinksmanager029f6b8e52c=\"9\" title=\"Download Scripts &amp; Themes &amp; Apps\" target=\"_blank\" rel=\"noopener\">app<\/a>lies to all languages using this model, with or without a garbage collector.<\/p>\n<h2 role=\"heading\" aria-level=\"2\"><span class=\"ez-toc-section\" id=\"Cleaning_Up_Your_Garbage\"><\/span>Cleaning Up Your Garbage<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Of course, it\u2019s not as simple as just \u201callocate once, and forget about it.\u201d If we never removed memory, we\u2019d have a\u00a0<em>memory leak<\/em>, which is <strong>very bad<\/strong> and will quickly eat up your machine\u2019s RAM. Allocations like local lists will go out of scope im<a href=\"https:\/\/buradabiliyorum.com\/en\/category\/social-mediaa\/\" data-internallinksmanager029f6b8e52c=\"1\" title=\"Social Media\" target=\"_blank\" rel=\"noopener\">media<\/a>tely, but without cleanup, would clog up the heap forever. So, programs must have a way to clean up memory that isn\u2019t needed anymore.<\/p>\n<p>In manual memory management languages like C++, memory is handled, well, manually. You must manually free memory and delete objects that you are no longer using, using a reference, or pointer, to that object\u2019s memory location. While that can be extremely fast, it isn\u2019t fun to code, and can lead to memory bugs and exploits. This is one of the major reasons C++ is seen as a \u201chard\u201d programming language to learn and code in.<\/p>\n<p>The alternative to manual management is having the machine do it for you automatically. This is what\u2019s know as garbage collection.<\/p>\n<p>A garbage collector\u00a0runs on a background thread and periodically scans your application\u2019s heap and stack, and looks for objects that no longer have any references. This means the object is worthless, and can be safely removed without affecting the program.<\/p>\n<p>For example, take the following pseudocode, which creates and \u201cdeletes\u201d an object<\/p>\n<pre>object refToObject = new object();&#13;\nrefToObject = null;<\/pre>\n<p>Since <code>refToObject<\/code>\u00a0no longer references the <code>new object()<\/code>\u00a0that was created, the garbage collector will see the the new object is dangling without a reference to it from anywhere, and remove it whenever it collects garbage next time.<\/p>\n<p>The garbage collector is also pretty smart, and is able to resolve circular dependencies. For example, if you have two objects that reference each other, but nothing else knows about them, it\u2019s garbage. In most cases, if an object doesn\u2019t have a reference chain starting from the root of the program and leading to the object, it\u2019s garbage.<\/p>\n<p>Garbage collection can be triggered at any time, usually:<\/p>\n<ul>\n<li>When the system is low on memory.<\/li>\n<li>The percentage of memory on the heap surpasses a certain threshold. This threshold is adjusted automatically, and is basically whenever the GC sees your program needs cleaning.<\/li>\n<li>When it\u2019s triggered manually, like with <code>GC.Collect()<\/code>.<\/li>\n<\/ul>\n<h2 role=\"heading\" aria-level=\"2\"><span class=\"ez-toc-section\" id=\"Impacts_On_Performance\"><\/span>Impacts On Performance<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Of course, garbage collection isn\u2019t free, at all. If it was, every language would use it. GC is slow, mostly because it needs to pause program execution to collect garbage.<\/p>\n<p>Think of it like this \u2014 your CPU can only work on one thing at a time. With C++, it\u2019s always working on your code, including the bits that delete memory. With a GC, your program doesn\u2019t delete memory, and runs up until it makes some garbage. Then, it\u2019s paused, and the CPU swaps to working on garbage collection. If it\u2019s doing this often, it can slow down application performance.<\/p>\n<p>Usually, it\u2019s fairly quick though, usually less than a couple of milliseconds at the most. For .NET, this depends on what kind of memory is being cleaned up though, as it keeps track of memory in different \u201cgenerations\u201d:<\/p>\n<ul>\n<li><strong>Generation 0<\/strong>, the youngest generation which contains short-lived objects like temporary variables.<\/li>\n<li><strong>Generation 1,<\/strong> which acts as a buffer between short and long term objects. If an object survives a garbage collection attempt, it will be \u201cpromoted\u201d to a higher generation.<\/li>\n<li><strong>Generation 2,<\/strong> the last one, which tracks long term objects.<\/li>\n<\/ul>\n<p>The GC will check objects in Gen0, then Gen1, then Gen2. Since they only contain temporary or newly created objects, cleaning up Gen0 and Gen1 is usually pretty fast, but Gen2 contains a lot of memory. Doing a \u201cfull garbage collection\u201d can be a lot slower than ephemeral garbage collections.<\/p>\n<h2 role=\"heading\" aria-level=\"2\"><span class=\"ez-toc-section\" id=\"How_To_Speed_Up_Performance\"><\/span>How To Speed Up Performance?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>So what can you do to prevent this? Well, at the end of the day, your garbage must be picked up. The only real thing you can do is reduce the amount of garbage your program is throwing around.<\/p>\n<p>One of the major ways to reduce garbage is to utilize\u00a0<strong>Object Pooling.<\/strong>\u00a0The core principle behind this is that it\u2019s often faster to reset objects to default than it is to make a new one and throw the old one away.<\/p>\n<p>For example, the following code iterates 10k times, and makes a new list every time to do something with it. However, this is horrible on the GC, so a better method is to make one big list, and clear it after you\u2019re done with it and want a new one.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"imgchk9 alignnone wp-image-6377 size-full\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/175e33fac924c4b7177e441ebccaddf3\/p\/uploads\/2020\/08\/ee32aeb8.png\" alt=\"This code will run 10,000 times, and leave 10,000 ownerless lists allocated in memory at the end of the function.\" width=\"402\" height=\"196\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><img loading=\"lazy\" decoding=\"async\" class=\"imgchk9 alignnone wp-image-6378 size-full\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/471b970761fd8ec90e40a703890e403f\/p\/uploads\/2020\/08\/fa713069.png\" alt=\"Run new List\u00a0before the loop to do the first allocation, then run .Clear\u00a0or reset data to save on memory space and garbage created.\" width=\"447\" height=\"218\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>In practice, this is usually done with a generic \u201cObject Pool,\u201d which manages a list of objects that it can \u201crent out\u201d to your program. When your code is done, it frees the object back to the pool, and resets it, ready to be used again when requested.\n<\/p><\/div>\n<blockquote><p><strong><span style=\"color: #ff6600;\">If you liked the article, do not forget to share it with your friends. Follow us on\u00a0<span style=\"color: #ff0000;\"><a style=\"color: #ff0000;\" href=\"https:\/\/news.google.com\/publications\/CAAqBwgKMLG0nwswvr63Aw\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">Google News<\/a><\/span>\u00a0too, click on the star and choose us from your favorites.<\/span><\/strong><\/p><\/blockquote>\n<blockquote>\n<p style=\"text-align: center;\">For forums sites go to <span style=\"color: #ff9900;\"><a style=\"color: #ff9900;\" href=\"https:\/\/forum.buradabiliyorum.com\/\" target=\"_blank\" rel=\"noopener\">Forum.BuradaBiliyorum.Com<\/a><\/span><\/strong><\/p>\n<\/blockquote>\n<blockquote>\n<p style=\"text-align: center;\"><strong>If you want to read more like this article, you can visit our <span style=\"color: #ff9900;\"><a style=\"color: #ff9900;\" href=\"https:\/\/en.buradabiliyorum.com\/technology\/\" target=\"_blank\" rel=\"noopener\">Technology category.<\/a><\/span><\/strong><\/p>\n<\/blockquote>\n<p><span style=\"color: black;\"><a style=\"color: #ff9900;\" href=\"https:\/\/www.cloudsavvyit.com\/10031\/what-is-garbage-collection-and-how-does-it-affect-your-programs-performance\/\" target=\"_blank\" rel=\"noopener\">Source<\/a><\/span><\/p>\n","protected":false},"excerpt":{"rendered":"<p>&#8220;#What Is Garbage Collection, and How Does It Affect Your Program\u2019s Performance? \u2013 CloudSavvy IT&#8221; Shutterstock\/Smit Garbage collection is a feature of many languages like C# and Java. While manual memory management like C++ can be quite fast, automatic garbage collection improves the quality-of-life for developers. However, it\u2019s important to understand the performance implications of&#8230;<\/p>\n","protected":false},"author":1,"featured_media":196800,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"fifu_image_url":"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/c42d50c4814e817d1516b7b42dd45a8a\/p\/uploads\/2021\/03\/5f73f353.png","fifu_image_alt":"","footnotes":""},"categories":[18],"tags":[],"class_list":["post-196799","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-technology"],"_links":{"self":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts\/196799","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/comments?post=196799"}],"version-history":[{"count":0,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts\/196799\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/media\/196800"}],"wp:attachment":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/media?parent=196799"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/categories?post=196799"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/tags?post=196799"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}