<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>dotnet-internals Archives - CodeJourney.net</title>
	<atom:link href="https://www.codejourney.net/tag/dotnet-internals/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.codejourney.net/tag/dotnet-internals/</link>
	<description>Become a better .NET full stack web developer</description>
	<lastBuildDate>Sun, 30 Jun 2019 10:11:38 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/cropped-512px-na-512px-JPEG-BEZ-NAPISU-1.jpg?fit=32%2C32&#038;ssl=1</url>
	<title>dotnet-internals Archives - CodeJourney.net</title>
	<link>https://www.codejourney.net/tag/dotnet-internals/</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">123174533</site>	<item>
		<title>[.NET Internals 10] Application execution model</title>
		<link>https://www.codejourney.net/net-internals-10-application-execution-model/</link>
					<comments>https://www.codejourney.net/net-internals-10-application-execution-model/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Thu, 11 Oct 2018 18:46:40 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[dotnet-internals]]></category>
		<guid isPermaLink="false">https://www.dsibinski.pl/?p=2907</guid>

					<description><![CDATA[<p>Knowing the idea and main benefits of JIT compilation from the previous post, we&#8217;ll now see how it fits into .NET applications execution model. By execution model I mean a process of having a .NET Framework application actually executed on the machine (CPU), starting from having its source code written. It contains all steps and&#8230;</p>
<p>The post <a href="https://www.codejourney.net/net-internals-10-application-execution-model/">[.NET Internals 10] Application execution model</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Knowing the idea and main benefits of JIT compilation <a href="https://www.codejourney.net/2018/09/net-internals-09-just-in-time-jit-compilation/" target="_blank" rel="noopener">from the previous post</a>, we&#8217;ll now see how it fits into .NET applications execution model.</p>
<p>By <em>execution model</em> I mean a process of having a .NET Framework application actually executed on the machine (CPU), starting from having its source code written. It contains all steps and actions necessary to happen in order to transform source code (like C#) into machine (assembly) code and execute it.</p>
<p><span id="more-2907"></span></p>
<h1>.NET languages standardization</h1>
<p>As we all know, .NET is just an execution platform. There are, however, a lot of programming languages which allow us to write code which can then be executed by the platform-specific (not language-specific!) CLR. In order to give programming languages&#8217; creators a set of rules which their language and its compiler must meet to be .NET-compliant, Microsoft defined a <em>Common Language Infrastructure</em> (CLI, also referred to as MSIL in the old days <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> ) which is also standardized by ISO and ECMA.</p>
<p>&nbsp;</p>
<p>The main goal of it is to define how the source code should be compiled to the Common Intermediate Language (CIL). As we <a href="https://www.codejourney.net/2018/09/net-internals-09-just-in-time-jit-compilation/" target="_blank" rel="noopener">already know</a>, the CIL should have a standardized format, because it&#8217;s then JIT-compiled to a platform-specific assembly code. Some of the most common implementations of CLI are .NET Framework, .NET Core and Mono. I recommend you to check <a href="http://mattwarren.org/2018/10/02/A-History-of-.NET-Runtimes/" target="_blank" rel="noopener">Matt Warren&#8217;s article on .NET Runtimes history</a> as well <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>&nbsp;</p>
<p>Common Language Infrastructure implies also some other aspects of the programming language and its compiler, including Common Type System, language-agnostic metadata and Common Language Specification. You can read more about it for instance <a href="https://en.wikipedia.org/wiki/Common_Language_Infrastructure" target="_blank" rel="noopener">here</a>.</p>
<p>This all allows us to use various programming languages, like C#, VB.NET, F# or JScript .NET to develop .NET applications. Anyone can still implement their own own .NET language &#8211; it &#8220;just&#8221; needs to conform to the standards.</p>
<p>There&#8217;s also another term <a href="https://blogs.msdn.microsoft.com/dotnet/2016/09/26/introducing-net-standard/" target="_blank" rel="noopener">introduced somewhat around .NET Core</a> &#8211; <em>.NET Standard</em>. Its purpose is to allow code sharing between various .NET implementations. It actually defines a set of APIs that each .NET platform should implement. More details <a href="https://docs.microsoft.com/en-us/dotnet/standard/net-standard" target="_blank" rel="noopener">here</a>.</p>
<p>This whole <em>standardization</em> makes us arriving to the .NET applications execution model, which is how every standards-compliant CLR application is executed.</p>
<h1>.NET execution model</h1>
<p>Independently of the language of choice, .NET application&#8217;s execution model can be described as the following <strong>4-steps process</strong>:</p>
<ol>
<li>Writing source code in a programming language of choice, including the usage of its compiler</li>
<li>Compiling source code to Common Intermediate Language (CIL)</li>
<li>Compiling CIL into native code &#8211; details of this step <a href="https://www.codejourney.net/2018/09/net-internals-09-just-in-time-jit-compilation/" target="_blank" rel="noopener">in the previous post</a></li>
<li>Execution of the native code.</li>
</ol>
<p>These steps are well-resented on the schema below and then described in details in the next sections.</p>
<p>&nbsp;</p>
<figure id="attachment_2917" aria-describedby="caption-attachment-2917" style="width: 639px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/NetExecutionModel.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" fetchpriority="high" decoding="async" data-attachment-id="2917" data-permalink="https://www.codejourney.net/net-internals-10-application-execution-model/netexecutionmodel/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/NetExecutionModel.png?fit=639%2C697&amp;ssl=1" data-orig-size="639,697" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="NetExecutionModel" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/NetExecutionModel.png?fit=639%2C697&amp;ssl=1" class="wp-image-2917 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/NetExecutionModel.png?resize=639%2C697&#038;ssl=1" alt="" width="639" height="697" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/NetExecutionModel.png?w=639&amp;ssl=1 639w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/NetExecutionModel.png?resize=275%2C300&amp;ssl=1 275w" sizes="(max-width: 639px) 100vw, 639px" /></a><figcaption id="caption-attachment-2917" class="wp-caption-text"><span style="font-size: 8pt;">.NET application execution model, <a href="https://www.telerik.com/blogs/understanding-net-just-in-time-compilation" target="_blank" rel="noopener">source</a></span></figcaption></figure>
<h2>Writing source code in a programming language of choice</h2>
<p>As mentioned before, .NET applications can be implemented using any language of choice, which is compliant with CLI. Another important part is a <strong>compiler</strong> &#8211; it defines a general syntax of the language, kinds of data types that can be used by a programmer etc. For instance, current open-source compiler for C# and Visual Basic is <a href="https://github.com/dotnet/roslyn" target="_blank" rel="noopener">Roslyn</a>.</p>
<p>In the end, role of the compiler is to <strong>transform the source code to its CIL equivalent</strong>.</p>
<p>The simplest possible complete application written in C# can look as follows:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist92409303" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-csharp_code-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="csharp_code.cs content, created by dsibinski on 05:45PM on October 11, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="csharp_code.cs">
<tr>
<td id="file-csharp_code-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-csharp_code-cs-LC1" class="blob-code blob-code-inner js-file-line">  using System;</td>
</tr>
<tr>
<td id="file-csharp_code-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-csharp_code-cs-LC2" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-csharp_code-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-csharp_code-cs-LC3" class="blob-code blob-code-inner js-file-line">  public class Program</td>
</tr>
<tr>
<td id="file-csharp_code-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-csharp_code-cs-LC4" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-csharp_code-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-csharp_code-cs-LC5" class="blob-code blob-code-inner js-file-line">      public static void Main()</td>
</tr>
<tr>
<td id="file-csharp_code-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-csharp_code-cs-LC6" class="blob-code blob-code-inner js-file-line">      {</td>
</tr>
<tr>
<td id="file-csharp_code-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-csharp_code-cs-LC7" class="blob-code blob-code-inner js-file-line">          Console.WriteLine(&quot;Hello Readers!&quot;);</td>
</tr>
<tr>
<td id="file-csharp_code-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-csharp_code-cs-LC8" class="blob-code blob-code-inner js-file-line">      }</td>
</tr>
<tr>
<td id="file-csharp_code-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-csharp_code-cs-LC9" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/7bdc8b50b6d5faefa7f90659e16db696/raw/258d3ec59d80cd06d9ae2cc7b23d9b97dabced47/csharp_code.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/7bdc8b50b6d5faefa7f90659e16db696#file-csharp_code-cs" class="Link--inTextBlock"><br />
          csharp_code.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<h2>Compiling source code to CIL</h2>
<p>After the source code is written, it must be compiled to CIL, which is an intermediate language understood by the CLR. On this level, the whole execution process <strong>becomes language-agnostic</strong>, which means that as soon as the code is compiled to CIL it is executed by the CLR and programming language’s features (e.g. its compiler) don&#8217;t play any more role.</p>
<p>CIL code looks more like assembly code, however containing some specific instructions. It&#8217;s still far more readable than native code. Apart from the direct transcript of source code, CIL contains metadata about the DLL/EXE assembly file.</p>
<p>The C# fragment presented in the previous section compiled to CIL by Roslyn looks as follows:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist92409385" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-roslyn_msil-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="roslyn_msil.cs content, created by dsibinski on 05:50PM on October 11, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="roslyn_msil.cs">
<tr>
<td id="file-roslyn_msil-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-roslyn_msil-cs-LC1" class="blob-code blob-code-inner js-file-line">  //  Microsoft (R) .NET Framework IL Disassembler.  Version 4.0.30319.33440</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-roslyn_msil-cs-LC2" class="blob-code blob-code-inner js-file-line">  //  Copyright (c) Microsoft Corporation.  All rights reserved.</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-roslyn_msil-cs-LC3" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-roslyn_msil-cs-LC4" class="blob-code blob-code-inner js-file-line">  // Metadata version: v4.0.30319</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-roslyn_msil-cs-LC5" class="blob-code blob-code-inner js-file-line">  .assembly extern mscorlib</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-roslyn_msil-cs-LC6" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-roslyn_msil-cs-LC7" class="blob-code blob-code-inner js-file-line">  .publickeytoken = (B7 7A 5C 56 19 34 E0 89 )                         // .z\V.4..</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-roslyn_msil-cs-LC8" class="blob-code blob-code-inner js-file-line">  .ver 4:0:0:0</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-roslyn_msil-cs-LC9" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-roslyn_msil-cs-LC10" class="blob-code blob-code-inner js-file-line">  .assembly &#39;0bigfb2c&#39;</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-roslyn_msil-cs-LC11" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-roslyn_msil-cs-LC12" class="blob-code blob-code-inner js-file-line">  .hash algorithm 0x00008004</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
<td id="file-roslyn_msil-cs-LC13" class="blob-code blob-code-inner js-file-line">  .ver 0:0:0:0</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
<td id="file-roslyn_msil-cs-LC14" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
<td id="file-roslyn_msil-cs-LC15" class="blob-code blob-code-inner js-file-line">  .module &#39;0bigfb2c.dll&#39;</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
<td id="file-roslyn_msil-cs-LC16" class="blob-code blob-code-inner js-file-line">  // MVID: {3DD8C852-9FE1-4825-8784-3D7200409F2F}</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L17" class="blob-num js-line-number js-blob-rnum" data-line-number="17"></td>
<td id="file-roslyn_msil-cs-LC17" class="blob-code blob-code-inner js-file-line">  .imagebase 0x10000000</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L18" class="blob-num js-line-number js-blob-rnum" data-line-number="18"></td>
<td id="file-roslyn_msil-cs-LC18" class="blob-code blob-code-inner js-file-line">  .file alignment 0x00000200</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L19" class="blob-num js-line-number js-blob-rnum" data-line-number="19"></td>
<td id="file-roslyn_msil-cs-LC19" class="blob-code blob-code-inner js-file-line">  .stackreserve 0x00100000</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L20" class="blob-num js-line-number js-blob-rnum" data-line-number="20"></td>
<td id="file-roslyn_msil-cs-LC20" class="blob-code blob-code-inner js-file-line">  .subsystem 0x0003       // WINDOWS_CUI</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L21" class="blob-num js-line-number js-blob-rnum" data-line-number="21"></td>
<td id="file-roslyn_msil-cs-LC21" class="blob-code blob-code-inner js-file-line">  .corflags 0x00000001    //  ILONLY</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L22" class="blob-num js-line-number js-blob-rnum" data-line-number="22"></td>
<td id="file-roslyn_msil-cs-LC22" class="blob-code blob-code-inner js-file-line">  // Image base: 0x01580000</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L23" class="blob-num js-line-number js-blob-rnum" data-line-number="23"></td>
<td id="file-roslyn_msil-cs-LC23" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L24" class="blob-num js-line-number js-blob-rnum" data-line-number="24"></td>
<td id="file-roslyn_msil-cs-LC24" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L25" class="blob-num js-line-number js-blob-rnum" data-line-number="25"></td>
<td id="file-roslyn_msil-cs-LC25" class="blob-code blob-code-inner js-file-line">  // =============== CLASS MEMBERS DECLARATION ===================</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L26" class="blob-num js-line-number js-blob-rnum" data-line-number="26"></td>
<td id="file-roslyn_msil-cs-LC26" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L27" class="blob-num js-line-number js-blob-rnum" data-line-number="27"></td>
<td id="file-roslyn_msil-cs-LC27" class="blob-code blob-code-inner js-file-line">  .class public auto ansi beforefieldinit Program</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L28" class="blob-num js-line-number js-blob-rnum" data-line-number="28"></td>
<td id="file-roslyn_msil-cs-LC28" class="blob-code blob-code-inner js-file-line">  extends[mscorlib] System.Object</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L29" class="blob-num js-line-number js-blob-rnum" data-line-number="29"></td>
<td id="file-roslyn_msil-cs-LC29" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L30" class="blob-num js-line-number js-blob-rnum" data-line-number="30"></td>
<td id="file-roslyn_msil-cs-LC30" class="blob-code blob-code-inner js-file-line">  .method public hidebysig static void Main() cil managed</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L31" class="blob-num js-line-number js-blob-rnum" data-line-number="31"></td>
<td id="file-roslyn_msil-cs-LC31" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L32" class="blob-num js-line-number js-blob-rnum" data-line-number="32"></td>
<td id="file-roslyn_msil-cs-LC32" class="blob-code blob-code-inner js-file-line">  // </td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L33" class="blob-num js-line-number js-blob-rnum" data-line-number="33"></td>
<td id="file-roslyn_msil-cs-LC33" class="blob-code blob-code-inner js-file-line">  .maxstack  8</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L34" class="blob-num js-line-number js-blob-rnum" data-line-number="34"></td>
<td id="file-roslyn_msil-cs-LC34" class="blob-code blob-code-inner js-file-line">  IL_0000:  nop</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L35" class="blob-num js-line-number js-blob-rnum" data-line-number="35"></td>
<td id="file-roslyn_msil-cs-LC35" class="blob-code blob-code-inner js-file-line">  IL_0001:  ldstr      &quot;Hello Readers!&quot;</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L36" class="blob-num js-line-number js-blob-rnum" data-line-number="36"></td>
<td id="file-roslyn_msil-cs-LC36" class="blob-code blob-code-inner js-file-line">  IL_0006:  call       void [mscorlib]</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L37" class="blob-num js-line-number js-blob-rnum" data-line-number="37"></td>
<td id="file-roslyn_msil-cs-LC37" class="blob-code blob-code-inner js-file-line">  System.Console::WriteLine(string)</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L38" class="blob-num js-line-number js-blob-rnum" data-line-number="38"></td>
<td id="file-roslyn_msil-cs-LC38" class="blob-code blob-code-inner js-file-line">  IL_000b:  nop</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L39" class="blob-num js-line-number js-blob-rnum" data-line-number="39"></td>
<td id="file-roslyn_msil-cs-LC39" class="blob-code blob-code-inner js-file-line">  IL_000c:  ret</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L40" class="blob-num js-line-number js-blob-rnum" data-line-number="40"></td>
<td id="file-roslyn_msil-cs-LC40" class="blob-code blob-code-inner js-file-line">  } // end of method Program::Main</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L41" class="blob-num js-line-number js-blob-rnum" data-line-number="41"></td>
<td id="file-roslyn_msil-cs-LC41" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L42" class="blob-num js-line-number js-blob-rnum" data-line-number="42"></td>
<td id="file-roslyn_msil-cs-LC42" class="blob-code blob-code-inner js-file-line">  .method public hidebysig specialname rtspecialname</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L43" class="blob-num js-line-number js-blob-rnum" data-line-number="43"></td>
<td id="file-roslyn_msil-cs-LC43" class="blob-code blob-code-inner js-file-line">  instance void  .ctor() cil managed</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L44" class="blob-num js-line-number js-blob-rnum" data-line-number="44"></td>
<td id="file-roslyn_msil-cs-LC44" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L45" class="blob-num js-line-number js-blob-rnum" data-line-number="45"></td>
<td id="file-roslyn_msil-cs-LC45" class="blob-code blob-code-inner js-file-line">  // </td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L46" class="blob-num js-line-number js-blob-rnum" data-line-number="46"></td>
<td id="file-roslyn_msil-cs-LC46" class="blob-code blob-code-inner js-file-line">  .maxstack  8</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L47" class="blob-num js-line-number js-blob-rnum" data-line-number="47"></td>
<td id="file-roslyn_msil-cs-LC47" class="blob-code blob-code-inner js-file-line">  IL_0000:  ldarg.0</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L48" class="blob-num js-line-number js-blob-rnum" data-line-number="48"></td>
<td id="file-roslyn_msil-cs-LC48" class="blob-code blob-code-inner js-file-line">  IL_0001:  call instance void [mscorlib]</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L49" class="blob-num js-line-number js-blob-rnum" data-line-number="49"></td>
<td id="file-roslyn_msil-cs-LC49" class="blob-code blob-code-inner js-file-line">  System.Object::.ctor()</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L50" class="blob-num js-line-number js-blob-rnum" data-line-number="50"></td>
<td id="file-roslyn_msil-cs-LC50" class="blob-code blob-code-inner js-file-line">  IL_0006:  ret</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L51" class="blob-num js-line-number js-blob-rnum" data-line-number="51"></td>
<td id="file-roslyn_msil-cs-LC51" class="blob-code blob-code-inner js-file-line">  } // end of method Program::.ctor</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L52" class="blob-num js-line-number js-blob-rnum" data-line-number="52"></td>
<td id="file-roslyn_msil-cs-LC52" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-roslyn_msil-cs-L53" class="blob-num js-line-number js-blob-rnum" data-line-number="53"></td>
<td id="file-roslyn_msil-cs-LC53" class="blob-code blob-code-inner js-file-line">  } // end of class Program</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/dd7ace10bbca0668bf6337078d96483c/raw/73a63091d164236be813bb771a43ecac0fc52f27/roslyn_msil.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/dd7ace10bbca0668bf6337078d96483c#file-roslyn_msil-cs" class="Link--inTextBlock"><br />
          roslyn_msil.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>A bit more than the original source code, isn&#8217;t it? <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>Firstly there is a metadata instructions section which contains information about the assembly, execution framework’s version, types used in the code and external references. Next there&#8217;s the actual CIL code (equivalent to C# code presented above) listed.</p>
<script>(function() {
	window.mc4wp = window.mc4wp || {
		listeners: [],
		forms: {
			on: function(evt, cb) {
				window.mc4wp.listeners.push(
					{
						event   : evt,
						callback: cb
					}
				);
			}
		}
	}
})();
</script><!-- Mailchimp for WordPress v4.12.2 - https://wordpress.org/plugins/mailchimp-for-wp/ --><form id="mc4wp-form-1" class="mc4wp-form mc4wp-form-2612" method="post" data-id="2612" data-name="Download a free guide form" ><div class="mc4wp-form-fields"><table bgcolor="#f2f6f5"><tr><td> <p><p>
    <label>
<h1 style="">
  <center>GET A FREE GUIDE <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f381.png" alt="🎁" class="wp-smiley" style="height: 1em; max-height: 1em;" /></center>
      </h1>        
      <h2 style="font-family: Helvetica">
        <center>16 STEPS TO BECOME <br/>.NET FULL STACK WEB DEVELOPER </br>IN 2025</center>
      </h2>
</p>
  <center><div>
	<input type="email" name="EMAIL" placeholder="Email address" required />
    <p>
    <input type="text" name="FNAME" placeholder="Your name"
    required="">
  </p>
  </div>
    <center>

	<center><input type="submit" value="DOWNLOAD THE FREE GUIDE" style="color: #7b1fa2; font-weight:bold; font-size: 20px" /></center>
<p style="font-size: 12px; font-style: italic;">After you sign up, I may be sending you some emails with additional free content from time to time.
<br/>No spam, only awesome stuff</p>
</p></td></tr></table>

</div><label style="display: none !important;">Leave this field empty if you're human: <input type="text" name="_mc4wp_honeypot" value="" tabindex="-1" autocomplete="off" /></label><input type="hidden" name="_mc4wp_timestamp" value="1778077245" /><input type="hidden" name="_mc4wp_form_id" value="2612" /><input type="hidden" name="_mc4wp_form_element_id" value="mc4wp-form-1" /><div class="mc4wp-response"></div></form><!-- / Mailchimp for WordPress Plugin -->
<h2>Compiling CIL into native code</h2>
<p>We&#8217;ve already covered this step in details in <a href="https://www.codejourney.net/2018/09/net-internals-09-just-in-time-jit-compilation/" target="_blank" rel="noopener">the previous post about Just-In-Time compilation</a>, which is just a bit more fancy name of this process <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Now you can see how and where it fits into .NET application&#8217;s execution model.</p>
<h3>Normal JIT compilation</h3>
<p>By default, JIT compilation is done in the place where &#8220;Normal JIT Compiler&#8221; is drawn on the schema below:</p>
<figure id="attachment_2920" aria-describedby="caption-attachment-2920" style="width: 580px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/NormalJit.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" decoding="async" data-attachment-id="2920" data-permalink="https://www.codejourney.net/net-internals-10-application-execution-model/normaljit/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/NormalJit.png?fit=580%2C613&amp;ssl=1" data-orig-size="580,613" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="NormalJit" data-image-description="" data-image-caption="&lt;p&gt;Normal JIT, source&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/NormalJit.png?fit=580%2C613&amp;ssl=1" class="wp-image-2920 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/NormalJit.png?resize=580%2C613&#038;ssl=1" alt="" width="580" height="613" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/NormalJit.png?w=580&amp;ssl=1 580w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/NormalJit.png?resize=284%2C300&amp;ssl=1 284w" sizes="(max-width: 580px) 100vw, 580px" /></a><figcaption id="caption-attachment-2920" class="wp-caption-text"><span style="font-size: 8pt;">Normal JIT, <a href="https://www.telerik.com/blogs/understanding-net-just-in-time-compilation" target="_blank" rel="noopener">source</a></span></figcaption></figure>
<p>IL instructions of a particular block of code, in the example diagram of a method <em>Foo()</em>, are JIT-compiled when the block is to be used for the first time. Then, this JIT-compiled code is stored as the JIT-ed equivalent of <em>Foo()</em> method’s code in the memory cache. Such native code is then executed and if the same block of code needs to be called again in the future, it will not be re-JIT-compiled, but instead the native code will be taken from the memory cache and executed again.</p>
<p>There&#8217;s a possibility to skip adding the native code into memory cache for future executions and it&#8217;s referred to as “Econo JIT Compilation”, however it&#8217;s not widely used and probably obsolete since few versions of .NET, so we won&#8217;t examine it here.</p>
<h3>Pre-JIT compilation</h3>
<p>The schema presented above changes a bit as soon as we want to use so called <em>Pre-JIT compilation</em>. <a href="https://www.codejourney.net/2018/09/net-internals-09-just-in-time-jit-compilation/#AOT" target="_blank" rel="noopener">We mentioned it already</a> and we know that one of the techniques to allow pre-JIT (or <em>ahead-of-time</em>) compilation is using Native Image Generator (ngen.exe) which allows to transform CIL assemblies into native code files and to store them as a file on the disk (in the Native Image Cache). It allows to natively compile the whole assemblies – it doesn&#8217;t allow to compile only single methods as JIT compiler does.</p>
<p>&nbsp;</p>
<p>Refer to the new version of the schema presented below to see how the process changes with NGen.</p>
<p>&nbsp;</p>
<figure id="attachment_2924" aria-describedby="caption-attachment-2924" style="width: 509px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/PreJit.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" decoding="async" data-attachment-id="2924" data-permalink="https://www.codejourney.net/net-internals-10-application-execution-model/prejit/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/PreJit.png?fit=509%2C614&amp;ssl=1" data-orig-size="509,614" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="PreJit" data-image-description="" data-image-caption="&lt;p&gt;Pre-JIT, source&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/PreJit.png?fit=509%2C614&amp;ssl=1" class="wp-image-2924 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/PreJit.png?resize=509%2C614&#038;ssl=1" alt="" width="509" height="614" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/PreJit.png?w=509&amp;ssl=1 509w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/10/PreJit.png?resize=249%2C300&amp;ssl=1 249w" sizes="(max-width: 509px) 100vw, 509px" /></a><figcaption id="caption-attachment-2924" class="wp-caption-text"><span style="font-size: 8pt;">Pre-JIT, <a href="https://www.telerik.com/blogs/understanding-net-just-in-time-compilation" target="_blank" rel="noopener">source</a></span></figcaption></figure>
<p>Normal and ahead-of-time CIL compilation modes provide different cons and pros, including:</p>
<ul>
<li>NGen delivers faster start-up time, especially in large applications used by many users in the same time, but requires more disk space and memory to store both the CIL and pre-compiled images,</li>
<li>JIT compilation at runtime can deliver faster code, because it targets the current platform of execution; NGen produces the native images with instructions that can be executed on all possible platforms, meaning it must use the oldest from currently used instructions sets to be backwards-compatible,</li>
<li>JIT is able to dynamically re-compile the code for a better performance depending on the execution conditions (e.g. by detecting a hot path in the executed code).</li>
</ul>
<p>Choosing one of the modes depends on your use case.</p>
<h2>Execution of the native code</h2>
<p>Finally, the code blocks are run by the CLR, which asks CPU to execute compiled instructions sets. If you&#8217;re interested in how CPU exactly works and executes the instructions, I recommend you watching <a href="https://www.youtube.com/watch?v=cNN_tTXABUA" target="_blank" rel="noopener">this YT video</a>.</p>
<h1>Summary</h1>
<p>We&#8217;ve seen today how the .NET applications are executed step-by-step, starting from source code (like C#) up to being actually executed by the processor.</p>
<p>I also encourage you to read &#8211; if you haven&#8217;t already &#8211; all the previous posts in the .NET Internals series. Just <a href="https://www.codejourney.net/tag/dotnet-internals/" target="_blank" rel="noopener">click here</a> to see them all <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>Let me know if you have any doubts or thoughts, I&#8217;m always open to your comments and opinions <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Especially the constructive ones pointing out some parts I omitted or didn&#8217;t describe precisely enough.</p>
<p>I hope it helped you learn something new <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>The post <a href="https://www.codejourney.net/net-internals-10-application-execution-model/">[.NET Internals 10] Application execution model</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/net-internals-10-application-execution-model/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2907</post-id>	</item>
		<item>
		<title>[.NET Internals 09] Just-In-Time (JIT) compilation</title>
		<link>https://www.codejourney.net/net-internals-09-just-in-time-jit-compilation/</link>
					<comments>https://www.codejourney.net/net-internals-09-just-in-time-jit-compilation/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Wed, 26 Sep 2018 18:10:35 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[dotnet-internals]]></category>
		<guid isPermaLink="false">https://www.dsibinski.pl/?p=2883</guid>

					<description><![CDATA[<p>Have you ever heard the term JIT? It&#8217;s an acronym for Just-In-Time. JIT compiler is a tool which performs the JIT compilation, which is a crucial feature of .NET applications. Let&#8217;s say a few more words on it today 🙂 What makes managed applications portable? As we know from the previous posts published within the series, .NET&#8230;</p>
<p>The post <a href="https://www.codejourney.net/net-internals-09-just-in-time-jit-compilation/">[.NET Internals 09] Just-In-Time (JIT) compilation</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<div>Have you ever heard the term <i>JIT</i>? It&#8217;s an acronym for Just-In-Time. <i>JIT compiler</i> is a tool which performs the <i>JIT compilation,</i> which is a crucial feature of .NET applications. Let&#8217;s say a few more words on it today <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></div>
<p><span id="more-2883"></span></p>
<div></div>
<h1>What makes managed applications portable?</h1>
<div>As we know from the previous posts <a href="https://www.codejourney.net/tag/dotnet-internals/" target="_blank" rel="noopener noreferrer">published within the series</a>, .NET Framework and CLR provide a lot of useful features for applications targeting the platform, such as <a href="http://internals" target="_blank" rel="noopener noreferrer">automatic memory management</a>. However, one of the main goals of managed runtimes&#8217; invention was to make implemented applications <em>portable</em>.</div>
<div></div>
<div></div>
<div>So what does it mean than an application is portable? It means that, first of all, it can be run on any kind of hardware. Ideally, it should also be software-agnostic (especially OS-agnostic). We can still observe this trend for instance by the fact that Microsoft created ans is actively developing a multi-platform <a href="https://github.com/dotnet/core" target="_blank" rel="noopener noreferrer">NET Core</a>.</div>
<div></div>
<div></div>
<div>Such portability not only makes the application possible to be launched on any hardware or software platform, but also releases developers from taking care about underlying low-level structures. For instance when working with <a href="https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/task-parallel-library-tpl" target="_blank" rel="noopener noreferrer">TPL</a>, the programmer normally doesn&#8217;t need to change his/her code taking into account the underlying hardware (e.g. number or architecture of CPUs). It&#8217;s the same for memory allocation (described in the previous posts) where many close-to-metal details differ based on operating system&#8217;s architecture (32/64 bit) &#8211; CLR handles it for us.</div>
<div></div>
<div></div>
<div>However, at some point, every application needs to be executed by the processor, which requires having a <i>machine code</i>  -assembly instructions understood and possible to be executed by the CPU. Depending on the OS&#8217;s or CPU&#8217;s architecture it&#8217;s sometimes necessary to use completely different CPU instructions sets in the assembly code. As you can guess, to make source code really portable it cannot be directly compiled to machine code. There&#8217;s something <em>intermediate</em> needed.</div>
<div></div>
<h1>Intermediate Language (IL)</h1>
<div>Because of the reasons described above, managed runtimes&#8217; programming languages source code (like C#, F# or Java) is not directly compiled to assembly language. Instead, it&#8217;s firstly compiled to an <i>intermediate language (IL)</i>.  CLR&#8217;s intermediate language is also referred to as MSIL (Microsoft Intermediate Language).</div>
<div></div>
<div></div>
<div>Compilation of source code into IL is performed by the particular language&#8217;s compiler. This is the process which happens when you build your app by pressing F6 in Visual Studio or <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/command-line-building-with-csc-exe" target="_blank" rel="noopener noreferrer">using csc.exe to compile your code</a>.</div>
<div>Source code -&gt; IL compilation is done by the particular language&#8217;s compiler. For instance, C# code is compiled by <a href="https://github.com/dotnet/roslyn" target="_blank" rel="noopener noreferrer">Roslyn</a>. which is a C# language&#8217;s compiler:</div>
<div></div>
<div>
<div>
<figure id="attachment_2884" aria-describedby="caption-attachment-2884" style="width: 1302px" class="wp-caption alignleft"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/Roslyn.png?ssl=1" target="_blank" rel="noopener noreferrer"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2884" data-permalink="https://www.codejourney.net/net-internals-09-just-in-time-jit-compilation/roslyn/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/Roslyn.png?fit=1302%2C186&amp;ssl=1" data-orig-size="1302,186" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Roslyn" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/Roslyn.png?fit=1024%2C146&amp;ssl=1" class="wp-image-2884 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/Roslyn.png?resize=1140%2C163&#038;ssl=1" alt="" width="1140" height="163" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/Roslyn.png?w=1302&amp;ssl=1 1302w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/Roslyn.png?resize=300%2C43&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/Roslyn.png?resize=768%2C110&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/Roslyn.png?resize=1024%2C146&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/Roslyn.png?resize=720%2C103&amp;ssl=1 720w" sizes="auto, (max-width: 1140px) 100vw, 1140px" /></a><figcaption id="caption-attachment-2884" class="wp-caption-text"><span style="font-size: 8pt;">Visual Studio&#8217;s build &#8211; Roslyn</span></figcaption></figure>
</div>
</div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<h2>Viewing MSIL</h2>
<div>In order to see the MSIL code contained in the compiled EXE/DLL files (like I showed you e.g. <a href="https://www.codejourney.net/2018/09/net-internals-07-unmanaged-resources-finalization-freachable-queue-and-dispose-pattern/" target="_blank" rel="noopener noreferrer">here</a> and <a href="https://www.codejourney.net/2018/08/net-internals-03-boxing-and-unboxing/" target="_blank" rel="noopener noreferrer">here</a>), you can use <a href="https://marketplace.visualstudio.com/items?itemName=SharpDevelopTeam.ILSpy" target="_blank" rel="noopener noreferrer">ILSpy Visual Studio extension</a>, which, when installed, adds a menu option in Visual Studio (Tools -&gt; ILSpy), where you can open any compiled file and view the IL code of contained objects:</div>
<div>
<figure id="attachment_2886" aria-describedby="caption-attachment-2886" style="width: 989px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/ILSpy_IL.png?ssl=1" target="_blank" rel="noopener noreferrer"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2886" data-permalink="https://www.codejourney.net/net-internals-09-just-in-time-jit-compilation/ilspy_il/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/ILSpy_IL.png?fit=989%2C348&amp;ssl=1" data-orig-size="989,348" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="ILSpy_IL" data-image-description="" data-image-caption="&lt;p&gt;ILSpy &amp;#8211; MSIL code&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/ILSpy_IL.png?fit=989%2C348&amp;ssl=1" class="wp-image-2886 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/ILSpy_IL.png?resize=989%2C348&#038;ssl=1" alt="" width="989" height="348" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/ILSpy_IL.png?w=989&amp;ssl=1 989w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/ILSpy_IL.png?resize=300%2C106&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/ILSpy_IL.png?resize=768%2C270&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/ILSpy_IL.png?resize=720%2C253&amp;ssl=1 720w" sizes="auto, (max-width: 989px) 100vw, 989px" /></a><figcaption id="caption-attachment-2886" class="wp-caption-text"><span style="font-size: 8pt;">ILSpy &#8211; MSIL code</span></figcaption></figure>
</div>
<div>
<div>What is actually compiled into IL code? For now we can say that the most important are methods (grouped into classes, namespaces etc. of course). There are also many other things compiled (even more than you would expect by looking at your source code), but we will focus on the methods for now.</p>
</div>
<div></div>
<div>OK, so we have the IL code now, but it cannot be understood by the CPU yet. How and when is it then compiled to assembly code?</div>
</div>
<h1>Just-In-Time (JIT) compilation</h1>
<h2>How Toyota brought us JIT?</h2>
<div>Let&#8217;s start by some historical background <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> In the early 1960s, Japanese engineers at Toyota had to reorganize their warehouse management, because they had very high storage costs &#8211; delivery of the parts from suppliers took a lot of time, because they ordered a lot in advance. Every delivery had to be handled by someone, so they needed a lot of employees. Ordered parts were stored in the warehouses for a long time, required a lot or storage space and maintenance.</div>
<div></div>
<div></div>
<div>In order to minimize the costs, they invented a <i>just-in-time manufacturing</i> (also known as T<i>oyota Production System</i>). Its main principle was to <b>order goods from the suppliers only when the minimal level of stocks on the warehouse was reached</b>. In effect, the goods were delivered <i>just in time</i> they were needed on the production line. It minimized the number of deliveries (and warehouse employees) and in the same time didn&#8217;t require that much storage space as before.</div>
<div></div>
<div>The whole idea can be imagined as the following flows order:</div>
<div>
<figure id="attachment_2889" aria-describedby="caption-attachment-2889" style="width: 728px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/Toyota_JIT.jpg?ssl=1" target="_blank" rel="noopener noreferrer"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2889" data-permalink="https://www.codejourney.net/net-internals-09-just-in-time-jit-compilation/toyota_jit/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/Toyota_JIT.jpg?fit=728%2C546&amp;ssl=1" data-orig-size="728,546" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Toyota_JIT" data-image-description="" data-image-caption="&lt;p&gt;Toyota Production System (JIT), source&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/Toyota_JIT.jpg?fit=728%2C546&amp;ssl=1" class="wp-image-2889 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/Toyota_JIT.jpg?resize=728%2C546&#038;ssl=1" alt="" width="728" height="546" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/Toyota_JIT.jpg?w=728&amp;ssl=1 728w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/Toyota_JIT.jpg?resize=300%2C225&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/Toyota_JIT.jpg?resize=720%2C540&amp;ssl=1 720w" sizes="auto, (max-width: 728px) 100vw, 728px" /></a><figcaption id="caption-attachment-2889" class="wp-caption-text"><span style="font-size: 8pt;">Toyota Production System (JIT), <a href="https://www.slideshare.net/nsjidnjkj/toyota-5458336" target="_blank" rel="noopener noreferrer">source</a></span></figcaption></figure>
</div>
<h2>JIT compiler</h2>
<div>
<div>Following Toyota&#8217;s success <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f600.png" alt="😀" class="wp-smiley" style="height: 1em; max-height: 1em;" /> , CLR creators introduced a <i>just-in-time (JIT)</i> <i>compiler</i> into the framework. Its role is to <b>compile intermediate language code into assembly language</b> according to hardware and operating system&#8217;s characteristics (depending on the machine on which the code is being JIT-compiled). Unlike unmanaged languages, in which the source code is compiled into machine language prior to program&#8217;s execution, IL is (by default) compiled to CPU instructions <b>at runtime</b>. That&#8217;s how .NET engineers made the machine code delivered on time to the CPU.</div>
<div></div>
</div>
<div>
<div></div>
<div>JIT compiler is a part of CLR (similarly to <a href="https://www.codejourney.net/2018/08/net-internals-04-what-is-garbage-collection-memory-allocation-in-net/" target="_blank" rel="noopener noreferrer">garbage collector</a>). To make things simple, it can be said that JIT compiles a particular method&#8217;s source code as soon as this method is called for the first time. Of course, it takes into account the hardware, e.g. the CPU type and its instructions set to produce correct assembly code. Such machine code is then saved in the cache and re-used every time the same method is called again within the same application&#8217;s execution. It means that the parts of the code which are not used (called) during the program&#8217;s execution may not be JIT-compiled at all.</div>
<div></div>
<div>Just-In-Time compilation is actually a combination of two approaches: ahead-of-time compilation and interpretation, mixing advantages and disadvantages of both. However, compiling IL code into assembly one at runtime allows for several interesting features like dynamic typing (ability to retrieve the actual object&#8217;s type at program&#8217;s execution). That&#8217;s why JIT compilation is often treated as a form of <i>dynamic compilation</i>.</div>
<div></div>
<div>Another advantage of having JIT compilation is that the source code we write is &#8220;further from the hardware&#8221;, so it can be made more readable and human-friendly, whereas the metal-touching stuff is &#8220;hidden&#8221; in the IL (kudos to MSIL developers!) <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></div>
<div></div>
</div>
<div>JIT compilation has also some cost &#8211; naturally it requires time to compile the code at runtime. On the other hand, various CPU units may have different powerful instructions sets or processing units that may be used in the assembly produced by the JIT, which wouldn&#8217;t be the case in ahead-of-time compilation (without any special tuning).</div>
<h2 id="AOT">Can we still compile ahead-of-time?</h2>
<div>If you really don&#8217;t like JIT (why would you?), there are ways to pre-JIT-compile your EXE/DLLs prior to an application&#8217;s execution. This is called <em>Pre-JIT compilation</em>. One of the reasons for that can be that a lot of users will run our application from the same EXE/DLL files, which would normally make JIT-compiling the IL for each user separately. In such case it may be relevant to pre-JIT-compile our application&#8217;s files for performance and memory usage reasons. It can be done using <a href="https://docs.microsoft.com/en-us/dotnet/framework/tools/ngen-exe-native-image-generator" target="_blank" rel="noopener noreferrer">NGen</a> (for all versions of .NET) or <a href="https://docs.microsoft.com/en-us/dotnet/framework/net-native/" target="_blank" rel="noopener noreferrer">.NET Native</a> (for .NET apps targeting Windows 10). We will not be describing these tools in details today (you can find more information on the Internet).</div>
<h1>Summary</h1>
<div>JIT compilation is a process of compiling an intermediate language (IL) into native (machine) code at runtime. It provides the portability of managed applications. It&#8217;s a very important concept to understand, as it&#8217;s introduced in a lot of currently used programming frameworks like Java, .NET and Android.</p>
</div>
<div>In one of the next posts we&#8217;ll dig into application execution model in .NET Framework, where we&#8217;ll see when and how exactly the JIT compilation process fits into the whole C#-&gt;CPU journey <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
</div>
<div>Finally, as always, remember that:</div>
<div>
<figure id="attachment_2892" aria-describedby="caption-attachment-2892" style="width: 300px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/george_meme.jpg?ssl=1" target="_blank" rel="noopener noreferrer"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2892" data-permalink="https://www.codejourney.net/net-internals-09-just-in-time-jit-compilation/george_meme/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/george_meme.jpg?fit=630%2C630&amp;ssl=1" data-orig-size="630,630" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="george_meme" data-image-description="" data-image-caption="&lt;p&gt;Source&lt;/p&gt;
" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/george_meme.jpg?fit=630%2C630&amp;ssl=1" class="wp-image-2892 size-medium" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/george_meme.jpg?resize=300%2C300&#038;ssl=1" alt="" width="300" height="300" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/george_meme.jpg?resize=300%2C300&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/george_meme.jpg?resize=150%2C150&amp;ssl=1 150w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/george_meme.jpg?w=630&amp;ssl=1 630w" sizes="auto, (max-width: 300px) 100vw, 300px" /></a><figcaption id="caption-attachment-2892" class="wp-caption-text"><a href="https://www.teepublic.com/t-shirt/2228544-funny-george-washington-history-meme" target="_blank" rel="noopener noreferrer"><span style="font-size: 8pt;">Source</span></a></figcaption></figure>
<p>so if you have your own opinion on JIT or any other remarks, <span style="text-decoration: underline;"><strong>don&#8217;t bother and share it in the comments</strong></span>! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
</div>
<p>The post <a href="https://www.codejourney.net/net-internals-09-just-in-time-jit-compilation/">[.NET Internals 09] Just-In-Time (JIT) compilation</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/net-internals-09-just-in-time-jit-compilation/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2883</post-id>	</item>
		<item>
		<title>[.NET Internals 08] What about Large Object Heap (LOH)?</title>
		<link>https://www.codejourney.net/net-internals-08-what-about-large-object-heap-loh/</link>
					<comments>https://www.codejourney.net/net-internals-08-what-about-large-object-heap-loh/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Wed, 12 Sep 2018 13:00:58 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[dotnet-internals]]></category>
		<guid isPermaLink="false">https://www.dsibinski.pl/?p=2812</guid>

					<description><![CDATA[<p>So far within the .NET Internals series we focused on Small Object Heap (SOH). We know, for instance, that the LOH is not compacted (by default) during garbage collection. So how is it actually handled by the GC? (De)allocating objects on LOH As we know from the second post, during allocating the memory only objects&#8230;</p>
<p>The post <a href="https://www.codejourney.net/net-internals-08-what-about-large-object-heap-loh/">[.NET Internals 08] What about Large Object Heap (LOH)?</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>So far within the <a href="https://www.codejourney.net/tag/dotnet-internals/" target="_blank" rel="noopener">.NET Internals series</a> we focused on Small Object Heap (SOH). We know, for instance, that the <a href="https://www.codejourney.net/2018/08/net-internals-05-garbage-collection-marking-collection-and-heaps-compaction/" target="_blank" rel="noopener">LOH is not compacted (by default) during garbage collection</a>. So how is it actually handled by the GC?<br />
<span id="more-2812"></span></p>
<h1>(De)allocating objects on LOH</h1>
<p>As we know from the <a href="https://www.codejourney.net/2018/08/net-internals-02-stack-and-heap-net-data-structures/" target="_blank" rel="noopener">second post</a>, during allocating the memory only objects of size greater than 85,000 bytes are placed on LOH. There are also some exceptions, like arrays of <span style="color: #ff6600; font-family: terminal, monaco, monospace;">double</span> which are put on LOH (in 32-bit architectures only) as soon as they reach 1000 (or more) elements (not something around 10626 elements as could be expected). This is quite important to know to be aware what kind of objects have impact on heap fragmentation (more details below).</p>
<p>&nbsp;</p>
<p>So we know when the objects are allocated on LOH, but when are they deallocated?</p>
<p>LOH is collected in the same time as the generation 2 collection occurs. It can be triggered if memory threshold for either gen 2 or LOH is exceeded. Conditions for garbage collection can be found <a href="https://www.codejourney.net/2018/08/net-internals-05-garbage-collection-marking-collection-and-heaps-compaction/" target="_blank" rel="noopener">in this post</a>.</p>
<p>That&#8217;s why keeping large LOH may affect the GC&#8217;s &#8211; and the whole application&#8217;s &#8211; performance.</p>
<h1>Garbage collection on LOH</h1>
<h2>LOH fragmentation</h2>
<p>The reason why Large Object Heap is not compacted (by default) is because it&#8217;s used to store big objects (&gt;85,000 bytes). Copying such amounts of data would seriously incur the performance of garbage collection process.</p>
<p>Anyway, memory of objects allocated on the LOH is reclaimed so it may eventually become fragmented:</p>
<figure id="attachment_2546" aria-describedby="caption-attachment-2546" style="width: 138px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/VirtualMemoryFragmentation.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2546" data-permalink="https://www.codejourney.net/net-internals-01-basics-of-memory-structure/virtualmemoryfragmentation/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/VirtualMemoryFragmentation.png?fit=138%2C305&amp;ssl=1" data-orig-size="138,305" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="VirtualMemoryFragmentation" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/VirtualMemoryFragmentation.png?fit=138%2C305&amp;ssl=1" class="wp-image-2546 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/VirtualMemoryFragmentation.png?resize=138%2C305&#038;ssl=1" alt="" width="138" height="305" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/VirtualMemoryFragmentation.png?w=138&amp;ssl=1 138w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/VirtualMemoryFragmentation.png?resize=136%2C300&amp;ssl=1 136w" sizes="auto, (max-width: 138px) 100vw, 138px" /></a><figcaption id="caption-attachment-2546" class="wp-caption-text"><span style="font-size: 8pt;">LOH fragmentation</span></figcaption></figure>
<p>We&#8217;ll see below how, but <strong>.NET keeps track of &#8220;Free space&#8221; memory blocks to know which chunks are available for new allocations on LOH</strong>. When allocating it looks for a block large enough to store the whole object.</p>
<p>&nbsp;</p>
<p>However, imagine that there are 2 free space blocks next to each other. Both were marked free, but they represented different objects (maybe they were next to each other on the heap because one referenced the other). What do you think GC will do? Will it treat them as two separate free memory blocks, making less chances for the next allocated object to fit into one of them?</p>
<p>Fortunately not. <strong>GC has an optimization introduced which makes such adjacent free memory chunks &#8220;merged&#8221; together</strong>:</p>
<figure id="attachment_2813" aria-describedby="caption-attachment-2813" style="width: 300px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/LOH_HolesMerging.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2813" data-permalink="https://www.codejourney.net/net-internals-08-what-about-large-object-heap-loh/loh_holesmerging/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/LOH_HolesMerging.png?fit=534%2C455&amp;ssl=1" data-orig-size="534,455" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="LOH_HolesMerging" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/LOH_HolesMerging.png?fit=534%2C455&amp;ssl=1" class="wp-image-2813 size-medium" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/LOH_HolesMerging.png?resize=300%2C256&#038;ssl=1" alt="" width="300" height="256" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/LOH_HolesMerging.png?resize=300%2C256&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/LOH_HolesMerging.png?w=534&amp;ssl=1 534w" sizes="auto, (max-width: 300px) 100vw, 300px" /></a><figcaption id="caption-attachment-2813" class="wp-caption-text"><span style="font-size: 8pt;">Free memory chunks &#8220;merged&#8221; on LOH</span></figcaption></figure>
<p>How does GC do it? Let&#8217;s see in more details.</p>
<h2>Free memory representation on LOH</h2>
<p>Instead of compacting Large Object Heap, garbage collector keeps the address ranges of not used large objects in a Free Space Table:</p>
<figure id="attachment_2815" aria-describedby="caption-attachment-2815" style="width: 900px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FreeSpaceTable.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2815" data-permalink="https://www.codejourney.net/net-internals-08-what-about-large-object-heap-loh/freespacetable/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FreeSpaceTable.png?fit=900%2C442&amp;ssl=1" data-orig-size="900,442" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="FreeSpaceTable" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FreeSpaceTable.png?fit=900%2C442&amp;ssl=1" class="wp-image-2815 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FreeSpaceTable.png?resize=900%2C442&#038;ssl=1" alt="" width="900" height="442" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FreeSpaceTable.png?w=900&amp;ssl=1 900w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FreeSpaceTable.png?resize=300%2C147&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FreeSpaceTable.png?resize=768%2C377&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FreeSpaceTable.png?resize=720%2C354&amp;ssl=1 720w" sizes="auto, (max-width: 900px) 100vw, 900px" /></a><figcaption id="caption-attachment-2815" class="wp-caption-text"><span style="font-size: 8pt;">Free Space Table, <a href="https://www.red-gate.com/library/under-the-hood-of-net-memory-management" target="_blank" rel="noopener">source</a></span></figcaption></figure>
<p>As you can see on the figure above, as soon as gen 2 collection run, address ranges of two unused objects were just added to the Free Space Table.</p>
<p>Now you can see that &#8220;merging&#8221; two adjacent free memory chunks is just a simple addition operation (or modification of one number in the table).</p>
<h2>Allocating memory on LOH</h2>
<p>As soon as a new large (&gt;85,000 bytes or applicable array) object is to be allocated on the managed heap, GC looks for a single &#8220;Free Space&#8221; block to hold it. However, it&#8217;s rather unlikely that the particular object&#8217;s size will fit into one of the free memory chunks. In that case, a new object will be allocated on the top of the heap (just after &#8216;Object D&#8217; on the figure above).</p>
<p>&nbsp;</p>
<p>It may happen that the memory obtained from the operating system for LOH is already used (<a href="https://www.codejourney.net/2018/07/net-internals-01-basics-of-memory-structure/" target="_blank" rel="noopener">read here</a> for more info about memory). Garbage collector then asks the operating system for more memory segments to be acquired for LOH. If it fails, gen 2 collection is triggered hoping that some memory blocks will be freed and then the allocation will be possible.</p>
<p>&nbsp;</p>
<p>Let&#8217;s now think about it for a while. We said previously that LOH collection triggers gen 2 collection. So trying to clean-up the Large Object Heap every time an allocation on it is made would be a potential performance killer.</p>
<p>&nbsp;</p>
<p>How does GC solve this issue? Well, in fact, after a lot of optimizations introduced to LOH management in .NET 4.5, the GC takes the following actions in order to make a new allocation of a large object:</p>
<ul>
<li>firstly, the GC tries to allocate new objects into one of the free space &#8220;holes&#8221; on the LOH (it&#8217;s quite simple to calculate whether any chunk is large enough to store the object knowing ranges of free space blocks from the Free Space Table).</li>
<li>if the above fails &#8211; garbage collector prefers to allocate new large objects at the end of the heap. Even though it may involve asking the OS for more memory segments, it&#8217;s been found to be easier and less consuming operation than performing full GC hoping to free some memory chunks on the LOH first.</li>
<li>only if the above fails (LOH cannot be &#8220;extended&#8221;) &#8211; GC triggers gen 2 collection hoping to free some additional space that could be used for a new allocation.</li>
</ul>
<p>What&#8217;s worth noticing is that <strong>this actions order seems to be good for performance, but can sometimes be a reason of memory fragmentation</strong>.</p>
<h2>Manual LOH compaction</h2>
<p>As you should already know from <a href="https://www.codejourney.net/2018/08/net-internals-05-garbage-collection-marking-collection-and-heaps-compaction/" target="_blank" rel="noopener">the previous article</a>, LOH can be compacted programmatically, by setting the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.runtime.gcsettings.largeobjectheapcompactionmode?view=netframework-4.7.2" target="_blank" rel="noopener">GCSettings.LargeObjectHeapCompactionMode</a> property. The simplest way to force LOH compaction is as the following snippet presents:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91845646" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-loh_manual_compaction-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="LOH_manual_compaction.cs content, created by dsibinski on 04:58PM on September 11, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="LOH_manual_compaction.cs">
<tr>
<td id="file-loh_manual_compaction-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-loh_manual_compaction-cs-LC1" class="blob-code blob-code-inner js-file-line">  GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;</td>
</tr>
<tr>
<td id="file-loh_manual_compaction-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-loh_manual_compaction-cs-LC2" class="blob-code blob-code-inner js-file-line">  GC.Collect();</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/c41faa4201d987b17102f0229dfa20cc/raw/4b9004f1d32a3576ff40271590ed0e3cc82130b2/LOH_manual_compaction.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/c41faa4201d987b17102f0229dfa20cc#file-loh_manual_compaction-cs" class="Link--inTextBlock"><br />
          LOH_manual_compaction.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>There might be some niche cases in which LOH compaction may be useful. More details and discussions can be found for example <a href="https://stackoverflow.com/questions/20035550/large-object-heap-compaction-when-is-it-good" target="_blank" rel="noopener">here</a>.</p>
<h2>Best practices working with LOH objects</h2>
<p>We can try to simply design our applications to use the less possible number of large objects, but let&#8217;s not exaggerate. We are living in a world where 8GBs of 2133MHz RAM costs sometimes less than 100$, so the memory is generally cheap <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>In principle, the rule seems to be simple: <strong>large objects we allocate should be reused (e.g. cached) as much as possible</strong>.</p>
<p>We should just keep in mind that allocation of large objects can be costly, because of a need to perform gen 2 collection in some cases before the object is allocated.</p>
<p>An example of potentially problematic large object can be a <a href="https://msdn.microsoft.com/en-us/library/ms972976.aspx" target="_blank" rel="noopener">ViewState</a> used in ASP.NET applications, size of which can easily exceed 85K. There are some good articles explaining how to not stupidly incur ASP.NET app&#8217;s performance using it, for instance <a href="https://dzone.com/articles/optimize-aspnet-performance-with-view-state-cachin" target="_blank" rel="noopener">this one</a>.</p>
<p>There are also a lot of tools which can be used to measure the memory state and performance of our applications (also its internal mechanisms like garbage collection, heaps compaction etc.) which we&#8217;ll surely cover in one of the next posts within <a href="https://www.codejourney.net/tag/dotnet-internals/" target="_blank" rel="noopener">the series</a> <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h1>Summary</h1>
<p>Today we examined &#8211; previously a bit forgotten &#8211; Large Object Heap. We saw how the information about free memory blocks on it is stored by .NET Framework and how new objects are allocated on it.</p>
<p>&nbsp;</p>
<p>I think it&#8217;s one of the next internal concepts of .NET worth knowing and understanding, even though in the common scenarios and business applications you probably won&#8217;t get into troubles with LOH. However, it may be practical and useful to know when working with some more memory-demanding applications like games.</p>
<p>I hope this post clarifies some LOH topics for you.</p>
<p><span style="text-decoration: underline;">Let me know if there are any topics you&#8217;d be interested in reading about</span>. I&#8217;m here to provide some value to you, so I&#8217;m open for your criticism and suggestions <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>Stay tuned!</p>
<p>&nbsp;</p>
<script>(function() {
	window.mc4wp = window.mc4wp || {
		listeners: [],
		forms: {
			on: function(evt, cb) {
				window.mc4wp.listeners.push(
					{
						event   : evt,
						callback: cb
					}
				);
			}
		}
	}
})();
</script><!-- Mailchimp for WordPress v4.12.2 - https://wordpress.org/plugins/mailchimp-for-wp/ --><form id="mc4wp-form-2" class="mc4wp-form mc4wp-form-2612" method="post" data-id="2612" data-name="Download a free guide form" ><div class="mc4wp-form-fields"><table bgcolor="#f2f6f5"><tr><td> <p><p>
    <label>
<h1 style="">
  <center>GET A FREE GUIDE <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f381.png" alt="🎁" class="wp-smiley" style="height: 1em; max-height: 1em;" /></center>
      </h1>        
      <h2 style="font-family: Helvetica">
        <center>16 STEPS TO BECOME <br/>.NET FULL STACK WEB DEVELOPER </br>IN 2025</center>
      </h2>
</p>
  <center><div>
	<input type="email" name="EMAIL" placeholder="Email address" required />
    <p>
    <input type="text" name="FNAME" placeholder="Your name"
    required="">
  </p>
  </div>
    <center>

	<center><input type="submit" value="DOWNLOAD THE FREE GUIDE" style="color: #7b1fa2; font-weight:bold; font-size: 20px" /></center>
<p style="font-size: 12px; font-style: italic;">After you sign up, I may be sending you some emails with additional free content from time to time.
<br/>No spam, only awesome stuff</p>
</p></td></tr></table>

</div><label style="display: none !important;">Leave this field empty if you're human: <input type="text" name="_mc4wp_honeypot" value="" tabindex="-1" autocomplete="off" /></label><input type="hidden" name="_mc4wp_timestamp" value="1778077246" /><input type="hidden" name="_mc4wp_form_id" value="2612" /><input type="hidden" name="_mc4wp_form_element_id" value="mc4wp-form-2" /><div class="mc4wp-response"></div></form><!-- / Mailchimp for WordPress Plugin -->
<p>The post <a href="https://www.codejourney.net/net-internals-08-what-about-large-object-heap-loh/">[.NET Internals 08] What about Large Object Heap (LOH)?</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/net-internals-08-what-about-large-object-heap-loh/feed/</wfw:commentRss>
			<slash:comments>7</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2812</post-id>	</item>
		<item>
		<title>[.NET Internals 07] Unmanaged resources: finalization, fReachable queue and dispose pattern</title>
		<link>https://www.codejourney.net/net-internals-07-unmanaged-resources-finalization-freachable-queue-and-dispose-pattern/</link>
					<comments>https://www.codejourney.net/net-internals-07-unmanaged-resources-finalization-freachable-queue-and-dispose-pattern/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Wed, 05 Sep 2018 13:00:22 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[dotnet-internals]]></category>
		<guid isPermaLink="false">https://www.dsibinski.pl/?p=2779</guid>

					<description><![CDATA[<p>Today we&#8217;re going to see how unmanaged resources are handled by .NET, what are finalization and fReachable queues and what&#8217;s the garbage collector&#8217;s role in it. We&#8217;ll also get to know what is a dispose pattern and see how to implement it. Unmanaged resources and finalizers First of all we should all get familiar with what&#8230;</p>
<p>The post <a href="https://www.codejourney.net/net-internals-07-unmanaged-resources-finalization-freachable-queue-and-dispose-pattern/">[.NET Internals 07] Unmanaged resources: finalization, fReachable queue and dispose pattern</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Today we&#8217;re going to see how unmanaged resources are handled by .NET, what are <em>finalization</em> and <em>fReachable queues</em> and what&#8217;s the garbage collector&#8217;s role in it. We&#8217;ll also get to know what is a <em>dispose pattern</em> and see how to implement it.<br />
<span id="more-2779"></span></p>
<h1>Unmanaged resources and finalizers</h1>
<p>First of all we should all get familiar with what <em>unmanaged resources</em> are. These ones can be files or folders on the disk, database connections, GUI elements or network resources. You can also think of them as some external elements we need to interact with in our applications through some protocol (e.g. database queries or file system manipulation methods). They&#8217;re called <em>unmanaged</em> not without a reason &#8211; <strong>any unmanaged resources accessed from .NET code will not be automatically cleaned by the garbage collector</strong>. That&#8217;s how they are <em>not(un)managed</em>.</p>
<p>Maybe you&#8217;ve heard about <a href="https://en.cppreference.com/w/cpp/language/destructor" target="_blank" rel="noopener">destructors in C++</a> &#8211; remember methods called after class&#8217;s name (like its constructor) starting with &#8216;~&#8217; character? This also exists in .NET, but it&#8217;s not what you&#8217;d expect from C++. In .NET, such methods are referred to as <strong>finalizers</strong>.</p>
<h2>Finalizers and destructors in .NET</h2>
<p>Nonetheless, you can define a finalizer in your class in one of the following ways:</p>
<p>&nbsp;</p>
<p><strong> Using &#8220;destructor-like&#8221; syntax:</strong></p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91695157" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-destructor_example-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="Destructor_Example.cs content, created by dsibinski on 07:36PM on September 03, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="Destructor_Example.cs">
<tr>
<td id="file-destructor_example-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-destructor_example-cs-LC1" class="blob-code blob-code-inner js-file-line">namespace UnmanagedResourcesTests</td>
</tr>
<tr>
<td id="file-destructor_example-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-destructor_example-cs-LC2" class="blob-code blob-code-inner js-file-line">{</td>
</tr>
<tr>
<td id="file-destructor_example-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-destructor_example-cs-LC3" class="blob-code blob-code-inner js-file-line">    class MyTestClass</td>
</tr>
<tr>
<td id="file-destructor_example-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-destructor_example-cs-LC4" class="blob-code blob-code-inner js-file-line">    {</td>
</tr>
<tr>
<td id="file-destructor_example-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-destructor_example-cs-LC5" class="blob-code blob-code-inner js-file-line">        ~MyTestClass()</td>
</tr>
<tr>
<td id="file-destructor_example-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-destructor_example-cs-LC6" class="blob-code blob-code-inner js-file-line">        {</td>
</tr>
<tr>
<td id="file-destructor_example-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-destructor_example-cs-LC7" class="blob-code blob-code-inner js-file-line">            Console.WriteLine(&quot;Finalizing my object!&quot;);</td>
</tr>
<tr>
<td id="file-destructor_example-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-destructor_example-cs-LC8" class="blob-code blob-code-inner js-file-line">        }</td>
</tr>
<tr>
<td id="file-destructor_example-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-destructor_example-cs-LC9" class="blob-code blob-code-inner js-file-line">    }</td>
</tr>
<tr>
<td id="file-destructor_example-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-destructor_example-cs-LC10" class="blob-code blob-code-inner js-file-line">}</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/c50e995d8697d7b27412789647abb372/raw/da9dc7058cfc1b1ccb57b878d2a4def0760ed953/Destructor_Example.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/c50e995d8697d7b27412789647abb372#file-destructor_example-cs" class="Link--inTextBlock"><br />
          Destructor_Example.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p><strong>Using Finalize() method:</strong></p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91695262" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-finalizer_example-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="Finalizer_Example.cs content, created by dsibinski on 07:44PM on September 03, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="Finalizer_Example.cs">
<tr>
<td id="file-finalizer_example-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-finalizer_example-cs-LC1" class="blob-code blob-code-inner js-file-line">namespace UnmanagedResourcesTests</td>
</tr>
<tr>
<td id="file-finalizer_example-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-finalizer_example-cs-LC2" class="blob-code blob-code-inner js-file-line">{</td>
</tr>
<tr>
<td id="file-finalizer_example-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-finalizer_example-cs-LC3" class="blob-code blob-code-inner js-file-line">    class MyTestClass</td>
</tr>
<tr>
<td id="file-finalizer_example-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-finalizer_example-cs-LC4" class="blob-code blob-code-inner js-file-line">    {</td>
</tr>
<tr>
<td id="file-finalizer_example-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-finalizer_example-cs-LC5" class="blob-code blob-code-inner js-file-line">        void Finalize()</td>
</tr>
<tr>
<td id="file-finalizer_example-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-finalizer_example-cs-LC6" class="blob-code blob-code-inner js-file-line">        {</td>
</tr>
<tr>
<td id="file-finalizer_example-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-finalizer_example-cs-LC7" class="blob-code blob-code-inner js-file-line">            Console.WriteLine(&quot;Finalizing my object!&quot;);</td>
</tr>
<tr>
<td id="file-finalizer_example-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-finalizer_example-cs-LC8" class="blob-code blob-code-inner js-file-line">        }</td>
</tr>
<tr>
<td id="file-finalizer_example-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-finalizer_example-cs-LC9" class="blob-code blob-code-inner js-file-line">    }</td>
</tr>
<tr>
<td id="file-finalizer_example-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-finalizer_example-cs-LC10" class="blob-code blob-code-inner js-file-line">}</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/a5becab104ef57f2c8c35d8f9c66b672/raw/c1b3c742398d331530cf161a2aad242a4b65dcad/Finalizer_Example.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/a5becab104ef57f2c8c35d8f9c66b672#file-finalizer_example-cs" class="Link--inTextBlock"><br />
          Finalizer_Example.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>If you examine the IL code of both versions, it turns out that the <strong>destructor can be seen as a syntax sugar for the finalizer</strong>. In fact, the <span style="color: #ff6600;">~MyTestClass()</span> method is translated into <span style="color: #ff6600;">Finalize()</span> method:</p>
<figure id="attachment_2781" aria-describedby="caption-attachment-2781" style="width: 698px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizeIL.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2781" data-permalink="https://www.codejourney.net/net-internals-07-unmanaged-resources-finalization-freachable-queue-and-dispose-pattern/finalizeil/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizeIL.png?fit=698%2C648&amp;ssl=1" data-orig-size="698,648" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="FinalizeIL" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizeIL.png?fit=698%2C648&amp;ssl=1" class="wp-image-2781 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizeIL.png?resize=698%2C648&#038;ssl=1" alt="" width="698" height="648" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizeIL.png?w=698&amp;ssl=1 698w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizeIL.png?resize=300%2C279&amp;ssl=1 300w" sizes="auto, (max-width: 698px) 100vw, 698px" /></a><figcaption id="caption-attachment-2781" class="wp-caption-text"><span style="font-size: 8pt;">Destructor translated into Finalize() in IL</span></figcaption></figure>
<p>The only difference is that &#8211; as you can see on the IL above &#8211; <span style="color: #ff6600;">Finalize()</span> method created by the compiler from the destructor is implicitly calling the <span style="color: #ff6600;">Finalize()</span> method on the base class of the object (you can see it in the <span style="color: #ff6600;">finally</span> block in the IL generated). So in case of using a destructor-like syntax, we are actually creating a finalizer by overriding <span style="color: #ff6600;">Finalize()</span> method, whereas when implementing a <span style="color: #ff6600;">Finalize()</span> method directly we do it as we&#8217;d use the <span style="color: #ff6600;">new</span> keyword (hiding base class&#8217;s implementation of <span style="color: #ff6600;">Finalize()</span> method).</p>
<h2>Will GC call the finalizer for me?</h2>
<p>As you may know, finalizers methods are normally used to clean-up some unmanaged resources (e.g. to release a file handle or database connection). You may think that as soon as your object is ready to be collected (nothing references it anymore), garbage collector will firstly call the finalizer (to ensure everything is cleaned up) and then reclaim the memory used by the object.</p>
<p><strong>Unfortunately not</strong>. If you think about it one more time &#8211; GC cannot know what&#8217;s inside your <span style="color: #ff6600;">Finalize()</span> method. You can put there the code which downloads the whole Internet just like that:</p>
<figure id="attachment_2784" aria-describedby="caption-attachment-2784" style="width: 490px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/WholeInternet.gif?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2784" data-permalink="https://www.codejourney.net/net-internals-07-unmanaged-resources-finalization-freachable-queue-and-dispose-pattern/wholeinternet/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/WholeInternet.gif?fit=490%2C260&amp;ssl=1" data-orig-size="490,260" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="WholeInternet" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/WholeInternet.gif?fit=490%2C260&amp;ssl=1" class="wp-image-2784 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/WholeInternet.gif?resize=490%2C260&#038;ssl=1" alt="" width="490" height="260" /></a><figcaption id="caption-attachment-2784" class="wp-caption-text"><a href="https://knowyourmeme.com/photos/53057-the-last-page-of-the-internet" target="_blank" rel="noopener"><span style="font-size: 8pt;">Source</span></a></figcaption></figure>
<p>&#8230; and even though we have nowadays a bit faster bandwidths than the one from the gif <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> , you can clearly see it wouldn&#8217;t be a good idea to block garbage collection because of some costly process being executed before the memory for the object is reclaimed.</p>
<p>In order to avoid the above-described scenario, which would slow down the GC&#8217;s work significantly, .NET contributors decided that the <strong>finalizers on the objects are called periodically on a separate thread, completely independently from the GC</strong>.</p>
<p>This way the main GC thread is not blocked. However, it adds a bit of complexity to the garbage collection process &#8211; continue reading for more details.</p>
<h1>Finalization mechanism</h1>
<p>As we said in <a href="https://www.codejourney.net/2018/08/net-internals-05-garbage-collection-marking-collection-and-heaps-compaction/" target="_blank" rel="noopener">one of the previous posts</a>, one of the various sources of references to objects in our .NET application (GC roots) are &#8220;objects finalization references&#8221;. Let&#8217;s now make this mysterious term clear.</p>
<p>&nbsp;</p>
<p>In order to prevent having a finalizable object (containing finalizer method) reclaimed before its <span style="color: #ff6600;">Finalize()</span> method is called (which happens independently from the GC as you already know), there&#8217;s a separate references list called <strong>finalization queue </strong>maintained by the GC. As soon as memory for a new finalizable object is allocated, a reference to it is also put on the finalization queue, which becomes a <em>finalization root</em> for this object (it&#8217;s not the same kind of root as &#8220;normal&#8221; GC roots &#8211; it&#8217;s treated a bit more differently).</p>
<p>The diagram below presents the memory state just after few new objects were allocated on the managed heap.</p>
<figure id="attachment_2790" aria-describedby="caption-attachment-2790" style="width: 504px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizationFreachableQueue1-1.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2790" data-permalink="https://www.codejourney.net/net-internals-07-unmanaged-resources-finalization-freachable-queue-and-dispose-pattern/finalizationfreachablequeue1-2/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizationFreachableQueue1-1.png?fit=504%2C398&amp;ssl=1" data-orig-size="504,398" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="FinalizationFreachableQueue1" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizationFreachableQueue1-1.png?fit=504%2C398&amp;ssl=1" class="wp-image-2790 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizationFreachableQueue1-1.png?resize=504%2C398&#038;ssl=1" alt="" width="504" height="398" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizationFreachableQueue1-1.png?w=504&amp;ssl=1 504w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizationFreachableQueue1-1.png?resize=300%2C237&amp;ssl=1 300w" sizes="auto, (max-width: 504px) 100vw, 504px" /></a><figcaption id="caption-attachment-2790" class="wp-caption-text"><span style="font-size: 8pt;">Finalization and fReachable queues before GC, <a href="https://www.dotnettricks.com/learn/netframework/net-garbage-collection-and-finalization-queue" target="_blank" rel="noopener">source</a></span></figcaption></figure>
<p>As you can see, objects <em>ob2</em>, <em>ob3</em>, <em>ob5</em>, <em>ob6</em> and <em>ob10 </em>are all placed on the finalization queue, which means all of them contain <span style="color: #ff6600;">Finalize()</span> method.</p>
<p>Within these objects, <em>ob2</em> and <em>ob5</em> don&#8217;t have any references (roots) &#8211; it&#8217;s visible on the left side (heap). It means that these two objects are not used (are not referenced by anything) so they&#8217;re ready to be garbage collected. However, each of them contains a finalization root on the finalization queue.</p>
<p>As soon as the next garbage collection occurs, <em>ob2</em> and <em>ob5</em> cannot be reclaimed straightaway, as there&#8217;s a <span style="color: #ff6600;">Finalize()</span> method to be called on them first. Instead, when GC examines these two objects, it sees that they are not referenced from &#8220;normal&#8221; roots, but they have finalization references on the finalization queue. If that&#8217;s the case, GC moves finalization reference to another data structure called <strong>fReachable queue </strong>(also visible on the diagram above).</p>
<p>After, both queues and the heap look as follows:</p>
<figure id="attachment_2791" aria-describedby="caption-attachment-2791" style="width: 496px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizationFreachableQueue2.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2791" data-permalink="https://www.codejourney.net/net-internals-07-unmanaged-resources-finalization-freachable-queue-and-dispose-pattern/finalizationfreachablequeue2/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizationFreachableQueue2.png?fit=496%2C386&amp;ssl=1" data-orig-size="496,386" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="FinalizationFreachableQueue2" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizationFreachableQueue2.png?fit=496%2C386&amp;ssl=1" class="wp-image-2791 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizationFreachableQueue2.png?resize=496%2C386&#038;ssl=1" alt="" width="496" height="386" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizationFreachableQueue2.png?w=496&amp;ssl=1 496w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/FinalizationFreachableQueue2.png?resize=300%2C233&amp;ssl=1 300w" sizes="auto, (max-width: 496px) 100vw, 496px" /></a><figcaption id="caption-attachment-2791" class="wp-caption-text"><span style="font-size: 8pt;">Finalization and fReachable queues after GC, <a href="https://www.dotnettricks.com/learn/netframework/net-garbage-collection-and-finalization-queue" target="_blank" rel="noopener">source</a></span></figcaption></figure>
<p>That&#8217;s what I meant by stating that finalization roots are &#8220;special&#8221; kind of GC roots. Apart from that, <em>ob2</em> and <em>ob5</em> are still seen as &#8220;rooted&#8221; (as still being referenced) and because of that are not reclaimed by the GC. In that moment, standard <a href="https://www.codejourney.net/2018/08/net-internals-06-generational-garbage-collection/" target="_blank" rel="noopener">generational GC rules</a> apply, so if the collection below was a gen 1 collection, both objects will be promoted to gen 2.</p>
<p>Periodically, the finalization runs on a separate thread exploring the fReachable queue and calling <span style="color: #ff6600;">Finalize()</span> method on each object referenced from it. Then it removes the reference to this object from the queue. At this moment, finalizable object becomes rootless and can be reclaimed in the next garbage collection cycle.</p>
<h1>Dispose for the rescue</h1>
<p>In order to unify usage of finalizers and allow developers to correctly free their resources without unnecessarily prolonging their objects&#8217; lifetime (as you saw above, finalizable objects stay uncollected for at least 1 more GC round than &#8220;normal&#8221; objects), programmer can (and should) implement a <strong><em>dispose pattern</em></strong>. The purpose of it is <strong>to allow the developer to free unmanaged resources &#8220;manually&#8221; as soon as they are not needed anymore</strong>.</p>
<p>&nbsp;</p>
<p>The framework also provides a <span style="color: #ff6600;"><a style="color: #ff6600;" href="https://docs.microsoft.com/en-us/dotnet/api/system.gc.suppressfinalize?view=netframework-4.7.2" target="_blank" rel="noopener">GC.SuppressFinalize</a></span> method which tells GC that the object has been manually disposed and no more finalization is necessary. As soon as it&#8217;s called, the object reference is removed from finalization/fReachable queue. The goal is to prevent finalizing the object twice.</p>
<h2>IDisposable</h2>
<p>.NET Framework provides a <a href="https://docs.microsoft.com/en-us/dotnet/api/system.idisposable?view=netframework-4.7.2" target="_blank" rel="noopener">System.IDisposable</a> interface which should be implemented by a class which works with unmanaged resources.</p>
<p>Sample implementation of dispose pattern can look as follows:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91713758" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-dispose_example-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="Dispose_example.cs content, created by dsibinski on 06:58PM on September 04, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="Dispose_example.cs">
<tr>
<td id="file-dispose_example-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-dispose_example-cs-LC1" class="blob-code blob-code-inner js-file-line">public class UnmanagedClass : IDisposable</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-dispose_example-cs-LC2" class="blob-code blob-code-inner js-file-line">{</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-dispose_example-cs-LC3" class="blob-code blob-code-inner js-file-line">    public void Dispose()</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-dispose_example-cs-LC4" class="blob-code blob-code-inner js-file-line">    {</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-dispose_example-cs-LC5" class="blob-code blob-code-inner js-file-line">        CleanUp(true);</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-dispose_example-cs-LC6" class="blob-code blob-code-inner js-file-line">        GC.SuppressFinalize(this);</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-dispose_example-cs-LC7" class="blob-code blob-code-inner js-file-line">    }</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-dispose_example-cs-LC8" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-dispose_example-cs-LC9" class="blob-code blob-code-inner js-file-line">    private void CleanUp(bool disposing)</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-dispose_example-cs-LC10" class="blob-code blob-code-inner js-file-line">    {</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-dispose_example-cs-LC11" class="blob-code blob-code-inner js-file-line">        if (disposing)</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-dispose_example-cs-LC12" class="blob-code blob-code-inner js-file-line">        {</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
<td id="file-dispose_example-cs-LC13" class="blob-code blob-code-inner js-file-line">            // any thread-specific cleanup code</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
<td id="file-dispose_example-cs-LC14" class="blob-code blob-code-inner js-file-line">        }</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
<td id="file-dispose_example-cs-LC15" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
<td id="file-dispose_example-cs-LC16" class="blob-code blob-code-inner js-file-line">        // cleaning unmanaged resources here</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L17" class="blob-num js-line-number js-blob-rnum" data-line-number="17"></td>
<td id="file-dispose_example-cs-LC17" class="blob-code blob-code-inner js-file-line">    }</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L18" class="blob-num js-line-number js-blob-rnum" data-line-number="18"></td>
<td id="file-dispose_example-cs-LC18" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L19" class="blob-num js-line-number js-blob-rnum" data-line-number="19"></td>
<td id="file-dispose_example-cs-LC19" class="blob-code blob-code-inner js-file-line">    public void Finalize()</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L20" class="blob-num js-line-number js-blob-rnum" data-line-number="20"></td>
<td id="file-dispose_example-cs-LC20" class="blob-code blob-code-inner js-file-line">    {</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L21" class="blob-num js-line-number js-blob-rnum" data-line-number="21"></td>
<td id="file-dispose_example-cs-LC21" class="blob-code blob-code-inner js-file-line">        CleanUp(false);</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L22" class="blob-num js-line-number js-blob-rnum" data-line-number="22"></td>
<td id="file-dispose_example-cs-LC22" class="blob-code blob-code-inner js-file-line">    }</td>
</tr>
<tr>
<td id="file-dispose_example-cs-L23" class="blob-num js-line-number js-blob-rnum" data-line-number="23"></td>
<td id="file-dispose_example-cs-LC23" class="blob-code blob-code-inner js-file-line">}</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/2c51fc4c0f2df3ec9c4c69efd6f3bb7b/raw/125032117302184cabb58e8d8a0ca9a96b80405b/Dispose_example.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/2c51fc4c0f2df3ec9c4c69efd6f3bb7b#file-dispose_example-cs" class="Link--inTextBlock"><br />
          Dispose_example.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>Implementing <span style="color: #ff6600;">IDisposable</span> interface only forces us to add <span style="color: #ff6600;">Dispose()</span> method. Inside, we perform the resources clean-up and call <span style="color: #ff6600;">GC.SuppressFinalize(this)</span> to mark our object as finalized. We also implemented a separate method, in the example called <span style="color: #ff6600;">CleanUp(bool disposing)</span>, which performs the actual releasing of unmanaged resources. But why do we need this <span style="color: #ff6600;">bool disposing</span> parameter?</p>
<p>&nbsp;</p>
<p>It may be important to differentiate when the resources cleanup is called directly from code (we&#8217;ll see how it can be done in the next section) or by the finalization thread. As you already know, finalization is executed periodically <strong>on a separate thread</strong>. It means that if our <span style="color: #ff6600;">UnmanagedClass</span> needs any thread-specific resources cleanup, it&#8217;s not a good idea to execute it on totally independent, finalization thread, which is out-of-context at that moment.</p>
<p>That&#8217;s why we added a boolean parameter to the <span style="color: #ff6600;">CleanUp</span> method, which will be set to &#8220;true&#8221; as soon as <span style="color: #ff6600;">Dispose()</span> method is called directly from code. In that case we know that we can execute thread-specific cleanup code.</p>
<p>Additionally, we implemented the <span style="color: #ff6600;">Finalize()</span> method, which also calls <span style="color: #ff6600;">CleanUp()</span>, but passing &#8220;false&#8221; parameter&#8217;s value. In that case, as the finalization thread is out-of-context, we shouldn&#8217;t execute thread-specific cleanup code. We should treat <span style="color: #ff6600;">Finalize()</span> method as a last resort in case <span style="color: #ff6600;">Dispose()</span> has not been called because of some reason.</p>
<p>You can also check <a href="https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose" target="_blank" rel="noopener">Microsoft dosc</a> to see what&#8217;s their recommendation on implementing IDisposable interface.</p>
<h2>Using statement</h2>
<p>As mentioned above, the programmer can explicitly call <span style="color: #ff6600;">Dispose()</span> method on the class:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91714024" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-dispose_manually-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="Dispose_manually.cs content, created by dsibinski on 07:10PM on September 04, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="Dispose_manually.cs">
<tr>
<td id="file-dispose_manually-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-dispose_manually-cs-LC1" class="blob-code blob-code-inner js-file-line">  UnmanagedClass myClass = new UnmanagedClass();</td>
</tr>
<tr>
<td id="file-dispose_manually-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-dispose_manually-cs-LC2" class="blob-code blob-code-inner js-file-line">  // working with the instance&#8230;</td>
</tr>
<tr>
<td id="file-dispose_manually-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-dispose_manually-cs-LC3" class="blob-code blob-code-inner js-file-line">  myClass.Dispose();</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/e8d933cf16b9a09aff19a97de6fc32ce/raw/78b5351e222055e3124a0eae88ad4b75fd0b6b56/Dispose_manually.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/e8d933cf16b9a09aff19a97de6fc32ce#file-dispose_manually-cs" class="Link--inTextBlock"><br />
          Dispose_manually.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>but there&#8217;s another &#8211; and preferred &#8211; way: wrapping usage of the class within <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement" target="_blank" rel="noopener">using</a> statement:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91714058" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-dispose_with_using-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="Dispose_with_using.cs content, created by dsibinski on 07:12PM on September 04, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="Dispose_with_using.cs">
<tr>
<td id="file-dispose_with_using-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-dispose_with_using-cs-LC1" class="blob-code blob-code-inner js-file-line">  using (UnmanagedClass myClass = new UnmanagedClass())</td>
</tr>
<tr>
<td id="file-dispose_with_using-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-dispose_with_using-cs-LC2" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-dispose_with_using-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-dispose_with_using-cs-LC3" class="blob-code blob-code-inner js-file-line">      // working with the instance&#8230;</td>
</tr>
<tr>
<td id="file-dispose_with_using-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-dispose_with_using-cs-LC4" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/aba29f9bdf87bc129be4948e1e4c9995/raw/53e114999bbaeec03f5fdfc9eb5b29848f0fb882/Dispose_with_using.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/aba29f9bdf87bc129be4948e1e4c9995#file-dispose_with_using-cs" class="Link--inTextBlock"><br />
          Dispose_with_using.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>How does <span style="color: #ff6600;">using</span> statement ensure that <span style="color: #ff6600;">Dispose()</span> is called on our object created within it?</p>
<p>Let&#8217;s see the IL:</p>
<figure id="attachment_2792" aria-describedby="caption-attachment-2792" style="width: 745px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/using_IL.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2792" data-permalink="https://www.codejourney.net/net-internals-07-unmanaged-resources-finalization-freachable-queue-and-dispose-pattern/using_il/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/using_IL.png?fit=745%2C763&amp;ssl=1" data-orig-size="745,763" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="using_IL" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/using_IL.png?fit=745%2C763&amp;ssl=1" class="wp-image-2792 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/using_IL.png?resize=745%2C763&#038;ssl=1" alt="" width="745" height="763" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/using_IL.png?w=745&amp;ssl=1 745w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/using_IL.png?resize=293%2C300&amp;ssl=1 293w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/09/using_IL.png?resize=720%2C737&amp;ssl=1 720w" sizes="auto, (max-width: 745px) 100vw, 745px" /></a><figcaption id="caption-attachment-2792" class="wp-caption-text"><span style="font-size: 8pt;">IL of <span style="color: #ff6600;">using</span> statement</span></figcaption></figure>
<p>As you can see, the compiler translates <span style="color: #ff6600;">using</span> statement into try-finally block. In the <span style="color: #ff6600;">finally</span> part <span style="color: #ff6600;">Dispose()</span> method is called on our object&#8217;s instance.</p>
<p>This way the compiler ensures that even if there&#8217;s any exception thrown in the <span style="color: #ff6600;">using</span> block, the object will be disposed. That&#8217;s why we should always work with objects that may use unmanaged resources in such a way.</p>
<h1>Summary</h1>
<p>In this 7th post from <a href="https://www.codejourney.net/tag/dotnet-internals/" target="_blank" rel="noopener">.NET Internals</a> series we examined how unmanaged resources are handled within .NET Framework and what&#8217;s the GC&#8217;s role in that process. We got to know two new GC-internal data structures: finalization and fReachable queues. In the end, we got familiar with dispose pattern and <span style="color: #ff6600;">using</span> statement.</p>
<p>I hope it helped you to clarify these topics a bit <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>See you next week! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<script>(function() {
	window.mc4wp = window.mc4wp || {
		listeners: [],
		forms: {
			on: function(evt, cb) {
				window.mc4wp.listeners.push(
					{
						event   : evt,
						callback: cb
					}
				);
			}
		}
	}
})();
</script><!-- Mailchimp for WordPress v4.12.2 - https://wordpress.org/plugins/mailchimp-for-wp/ --><form id="mc4wp-form-3" class="mc4wp-form mc4wp-form-2612" method="post" data-id="2612" data-name="Download a free guide form" ><div class="mc4wp-form-fields"><table bgcolor="#f2f6f5"><tr><td> <p><p>
    <label>
<h1 style="">
  <center>GET A FREE GUIDE <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f381.png" alt="🎁" class="wp-smiley" style="height: 1em; max-height: 1em;" /></center>
      </h1>        
      <h2 style="font-family: Helvetica">
        <center>16 STEPS TO BECOME <br/>.NET FULL STACK WEB DEVELOPER </br>IN 2025</center>
      </h2>
</p>
  <center><div>
	<input type="email" name="EMAIL" placeholder="Email address" required />
    <p>
    <input type="text" name="FNAME" placeholder="Your name"
    required="">
  </p>
  </div>
    <center>

	<center><input type="submit" value="DOWNLOAD THE FREE GUIDE" style="color: #7b1fa2; font-weight:bold; font-size: 20px" /></center>
<p style="font-size: 12px; font-style: italic;">After you sign up, I may be sending you some emails with additional free content from time to time.
<br/>No spam, only awesome stuff</p>
</p></td></tr></table>

</div><label style="display: none !important;">Leave this field empty if you're human: <input type="text" name="_mc4wp_honeypot" value="" tabindex="-1" autocomplete="off" /></label><input type="hidden" name="_mc4wp_timestamp" value="1778077248" /><input type="hidden" name="_mc4wp_form_id" value="2612" /><input type="hidden" name="_mc4wp_form_element_id" value="mc4wp-form-3" /><div class="mc4wp-response"></div></form><!-- / Mailchimp for WordPress Plugin -->
<p>The post <a href="https://www.codejourney.net/net-internals-07-unmanaged-resources-finalization-freachable-queue-and-dispose-pattern/">[.NET Internals 07] Unmanaged resources: finalization, fReachable queue and dispose pattern</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/net-internals-07-unmanaged-resources-finalization-freachable-queue-and-dispose-pattern/feed/</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2779</post-id>	</item>
		<item>
		<title>[.NET Internals 06] Generational garbage collection</title>
		<link>https://www.codejourney.net/net-internals-06-generational-garbage-collection/</link>
					<comments>https://www.codejourney.net/net-internals-06-generational-garbage-collection/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Wed, 29 Aug 2018 13:00:52 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[dotnet-internals]]></category>
		<guid isPermaLink="false">http://www.dsibinski.pl/?p=2741</guid>

					<description><![CDATA[<p>Continuing .NET Internals series on the blog, today we&#8217;re going to see what is generational garbage collection. You&#8217;ll also get to know what is a card table data structure and for what it&#8217;s used 🙂 Heaps generations As we know from this post, heaps used by .NET process to allocate reference objects are allocated on&#8230;</p>
<p>The post <a href="https://www.codejourney.net/net-internals-06-generational-garbage-collection/">[.NET Internals 06] Generational garbage collection</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Continuing .<a href="https://www.codejourney.net/tag/dotnet-internals/" target="_blank" rel="noopener">NET Internals series on the blog</a>, today we&#8217;re going to see what is <em>generational garbage collection</em>. You&#8217;ll also get to know what is a <em>card table</em> data structure and for what it&#8217;s used <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /><br />
<span id="more-2741"></span></p>
<h1>Heaps generations</h1>
<p>As we know from <a href="https://www.codejourney.net/2018/08/net-internals-02-stack-and-heap-net-data-structures/" target="_blank" rel="noopener">this post</a>, heaps used by .NET process to allocate reference objects are allocated on different kinds of heaps. In <a href="https://www.codejourney.net/2018/08/net-internals-05-garbage-collection-marking-collection-and-heaps-compaction/" target="_blank" rel="noopener">the previous article</a> we also got to know that only Small Object Heap (SOH) is the subject of compaction process. Large Object Heap (LOH) is not compacted because of the performance reasons.</p>
<p>This is however not the only optimization introduced by GC contributors into Small Object Heap. SOH in .NET is also divided into <strong>3 generations</strong>:</p>
<ul>
<li>Generation 0 &#8211; containing newly created objects, which did not have any collection performed on them so far,</li>
<li>Generation 1 &#8211; storing objects that survived a single garbage collection (were not reclaimed during it because of still being in use),</li>
<li>Generation 2 &#8211; keeping long-lived objects that survived two or more GC cycles.</li>
</ul>
<p><span style="font-size: 10pt;">LOH is not divided into generations. More details on LOH management in the article linked just before the &#8220;Summary&#8221; section below.</p>
<p></span></p>
<p>Thanks to such a division of managed heap, the actual collection is performed not on the whole heap, but only on one of the generations, where:</p>
<blockquote>
<p><em>to perform a collection on generation X</em> == to collect objects on generation X and all its younger generations</p>
</blockquote>
<p>That&#8217;s why a <strong>generation 2 collection is knows as a full garbage collection</strong>. During this process objects present on all heaps (on all generations: gen 0, gen 1 and gen 2) are examined and reclaimed. Obviously, this collection is also the most costly one.</p>
<h1>Collection survivors</h1>
<p>In that place we should introduce a term <em>collection survivor</em>. It can be defined as an object which <em>survives</em> the collection (is not collected during GC collection cycle as it&#8217;s still referenced by something).</p>
<p>Knowing that, the following &#8220;promotion rules&#8221; can be defined:</p>
<ul>
<li>object <strong>survives</strong> <strong>generation 0</strong> collection =&gt; object is <strong>promoted to generation 1</strong>,</li>
<li>object <strong>survives generation 1</strong> collection =&gt; object is <strong>promoted to generation 2</strong>,</li>
<li>object <strong>survives generation 2</strong> collection =&gt; object <strong>stays in generation 2</strong>.</li>
</ul>
<h1>Collection thresholds in generations</h1>
<p>In the <a href="https://www.codejourney.net/2018/08/net-internals-05-garbage-collection-marking-collection-and-heaps-compaction/" target="_blank" rel="noopener">5th post in the series</a>, it was mentioned that one of the conditions on which the garbage collection can be triggered is when &#8220;the memory used by the objects on the managed heap exceeds some defined threshold&#8221;. In fact, this is not a single threshold, but several thresholds. More precisely, there&#8217;s a separate one per generation. As soon as size of all objects in a particular generation exceeds threshold&#8217;s value, the collection is started.</p>
<p>In the beginning, the thresholds&#8217; values for each generation are initialized to the following values:</p>
<ul>
<li>gen 0: ~256K,</li>
<li>gen 1: ~2MBs,</li>
<li>gen 2: ~10MBs.</li>
</ul>
<p>Nonetheless, these are only <strong>initial</strong> values and are adjusted by the GC at runtime. One of the conditions to increase a particular threshold&#8217;s value is then the survival rate in a generation is high (more objects from particular generation are either promoted to the next one or stay in generation 2), which makes the GC cycles to run less frequently (the condition of exceeding the threshold is not met that often).</p>
<p>This approach seems reasonable, as the main goal of GC is to collect as many objects as possible and reclaim their memory, not to &#8220;waste time&#8221; only to get to know that most of the objects are still in use.</p>
<p>In general, CLR tries to find a balance between two factors:</p>
<ul>
<li>not letting application&#8217;s working memory set to get too big,</li>
<li>not allowing GC to take too much time.</li>
</ul>
<h1>Structure of generational heap</h1>
<p>The diagram below presents how SOH actually looks like being divided into above-described 3 generations:</p>
<figure id="attachment_2747" aria-describedby="caption-attachment-2747" style="width: 640px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/SOH_Generations.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2747" data-permalink="https://www.codejourney.net/net-internals-06-generational-garbage-collection/soh_generations/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/SOH_Generations.png?fit=640%2C399&amp;ssl=1" data-orig-size="640,399" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="SOH_Generations" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/SOH_Generations.png?fit=640%2C399&amp;ssl=1" class="wp-image-2747 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/SOH_Generations.png?resize=640%2C399&#038;ssl=1" alt="" width="640" height="399" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/SOH_Generations.png?w=640&amp;ssl=1 640w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/SOH_Generations.png?resize=300%2C187&amp;ssl=1 300w" sizes="auto, (max-width: 640px) 100vw, 640px" /></a><figcaption id="caption-attachment-2747" class="wp-caption-text"><span style="font-size: 8pt;">SOH &#8211; generations, <a href="https://www.red-gate.com/library/under-the-hood-of-net-memory-management" target="_blank" rel="noopener">source</a></span></figcaption></figure>
<p>As can be noticed, the next object pointer (you can read more about it <a href="https://www.codejourney.net/2018/08/net-internals-04-what-is-garbage-collection-memory-allocation-in-net/" target="_blank" rel="noopener">in this post</a>) refers to the place after the last object in generation 0. That&#8217;s how it happens that newly created objects are always allocated in generation 0.</p>
<h1>Generational GC cycle</h1>
<p>The following schema very clearly presents how the full generational collection looks like (click to enlarge to see it clearly):</p>
<figure id="attachment_2748" aria-describedby="caption-attachment-2748" style="width: 1429px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Generations_Collection.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2748" data-permalink="https://www.codejourney.net/net-internals-06-generational-garbage-collection/generations_collection/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Generations_Collection.png?fit=1429%2C553&amp;ssl=1" data-orig-size="1429,553" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Generations_Collection" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Generations_Collection.png?fit=1024%2C396&amp;ssl=1" class="wp-image-2748 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Generations_Collection.png?resize=1140%2C441&#038;ssl=1" alt="" width="1140" height="441" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Generations_Collection.png?w=1429&amp;ssl=1 1429w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Generations_Collection.png?resize=300%2C116&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Generations_Collection.png?resize=768%2C297&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Generations_Collection.png?resize=1024%2C396&amp;ssl=1 1024w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Generations_Collection.png?resize=720%2C279&amp;ssl=1 720w" sizes="auto, (max-width: 1140px) 100vw, 1140px" /></a><figcaption id="caption-attachment-2748" class="wp-caption-text"><span style="font-size: 8pt;">Full GC, <a href="https://www.telerik.com/blogs/understanding-net-garbage-collection" target="_blank" rel="noopener">source</a></span></figcaption></figure>
<p>The first step is generation 0 collection. You can notice that objects <em>H</em> and <em>D</em> are not referenced by anything, so after the first cycle on gen 0 is performed, these objects are reclaimed and not promoted to gen 1. The same happens with object <em>F</em>, which is not being referenced to anymore when the collection on generation 1 is performed &#8211; that&#8217;s why it&#8217;s reclaimed during this step and not promoted to generation 2. In the end of the full GC cycle, only still-referenced objects stay on generation 2.</p>
<p>What&#8217;s also important to notice is that <strong>after each collection generation 0 becomes empty</strong> (contains no objects). Generation 1 may still contain objects promoted from generation 0 and generation 2 may contain long-lived objects.</p>
<h1>Why is static data harmful for GC?</h1>
<p>Having the knowledge presented in this post, we can deduce that the more objects are stored on a generation the longer collection process lasts. What we should also already be able to see is that generation 2 contains long-lived objects which are mostly static or global objects that survive garbage collection cycles (as there&#8217;s always a &#8220;live&#8221; reference to them in the application).</p>
<p>Of course, there are some reasons why static data can be justified (e.g. server-side apps storing some context<span style="font-size: 1rem;">), but <strong>normally using static data should be avoided as much as possible and reasonable</strong>. I think you already know why &#8211; it simply incurs the application&#8217;s performance by making garbage collector&#8217;s work harder and longer.</span></p>
<h1>Cross-generation references</h1>
<p>There&#8217;s also one very interesting issue in having the managed heap divided into generations. Can you imagine the case, when an object is already promoted to gen 2, but one of its reference-typed properties has just been initialized in gen 0? Consider the following code:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91541541" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-generations_crossref-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="Generations_crossRef.cs content, created by dsibinski on 05:30PM on August 25, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="Generations_crossRef.cs">
<tr>
<td id="file-generations_crossref-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-generations_crossref-cs-LC1" class="blob-code blob-code-inner js-file-line">  public class GuyFromGen2</td>
</tr>
<tr>
<td id="file-generations_crossref-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-generations_crossref-cs-LC2" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-generations_crossref-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-generations_crossref-cs-LC3" class="blob-code blob-code-inner js-file-line">      private YoungObject _youngObject;</td>
</tr>
<tr>
<td id="file-generations_crossref-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-generations_crossref-cs-LC4" class="blob-code blob-code-inner js-file-line">      public void CreateYoungObject()</td>
</tr>
<tr>
<td id="file-generations_crossref-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-generations_crossref-cs-LC5" class="blob-code blob-code-inner js-file-line">      {</td>
</tr>
<tr>
<td id="file-generations_crossref-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-generations_crossref-cs-LC6" class="blob-code blob-code-inner js-file-line">          _youngObject = new YoungObject();</td>
</tr>
<tr>
<td id="file-generations_crossref-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-generations_crossref-cs-LC7" class="blob-code blob-code-inner js-file-line">      }</td>
</tr>
<tr>
<td id="file-generations_crossref-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-generations_crossref-cs-LC8" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/c03d860c4066d40d029cf74b4dc5b90b/raw/9f4dadbef535b000ca164df736704e9df8ed1a71/Generations_crossRef.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/c03d860c4066d40d029cf74b4dc5b90b#file-generations_crossref-cs" class="Link--inTextBlock"><br />
          Generations_crossRef.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>Let&#8217;s assume that an instance of <span style="color: #ff6600;">GuyFromGen2</span> has already been created long time ago and it&#8217;s already promoted to generation 2. At this moment someone calls <span style="color: #ff6600;">CreateYoungObject()</span> method, which initializes <span style="color: #ff6600;">_youngObject</span> variable. This makes the &#8220;parent&#8221; instance of <span style="color: #ff6600;">GuyFromGen2 <span style="color: #333333;">holding a reference to its instance object located in gen 0. </p>
<p></span></span></p>
<p>When there&#8217;s a generation 0 collection triggered (which, as we said, examines only objects in generation 0) at this exact moment, it would find <span style="color: #ff6600;">_youngObject</span> allocated on the heap having no gen 0 references to it (as it doesn&#8217;t check gen 2 references during gen 0 collection) so it would assume the object not being used and reclaim its memory.</p>
<p>Fortunately, .NET has a solution for this issue &#8211; <strong>card table</strong> data structure.</p>
<h2>Card table data structure</h2>
<p>Card table is used by .NET&#8217;s memory management system to store information about objects from older generation (gen 2 in that case) that reference younger objects (from gen 0 or gen 1). The execution engine adds an entry into card table as soon as any reference to gen 0 or gen 1 object is created &#8220;inside&#8221; gen 2 object.</p>
<p>For performance optimization reasons the card table stores this information per &#8220;bit&#8221;, which represents 128 bytes (or 256 bytes in 64-bit architectures) of managed memory. That&#8217;s how the card table can be imagined:</p>
<figure id="attachment_2751" aria-describedby="caption-attachment-2751" style="width: 696px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Card_Table.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2751" data-permalink="https://www.codejourney.net/net-internals-06-generational-garbage-collection/card_table/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Card_Table.png?fit=696%2C453&amp;ssl=1" data-orig-size="696,453" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Card_Table" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Card_Table.png?fit=696%2C453&amp;ssl=1" class="wp-image-2751 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Card_Table.png?resize=696%2C453&#038;ssl=1" alt="" width="696" height="453" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Card_Table.png?w=696&amp;ssl=1 696w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Card_Table.png?resize=300%2C195&amp;ssl=1 300w" sizes="auto, (max-width: 696px) 100vw, 696px" /></a><figcaption id="caption-attachment-2751" class="wp-caption-text"><span style="font-size: 8pt;">Card table, <a href="https://www.red-gate.com/library/under-the-hood-of-net-memory-management" target="_blank" rel="noopener">source</a></span></figcaption></figure>
<p>Then, as soon as gen 0 or gen 1 collection takes place, apart from examining references only from the particular generation&#8217;s roots, GC also checks which memory ranges have their bits set to 1, finds out which objects are allocated within these memory ranges and treats them as potential GC roots (analyzing what these objects reference).</p>
<p>What&#8217;s more, as <a href="https://twitter.com/konradkokosa" target="_blank" rel="noopener">Konrad</a> pointed out in his comment, because of write barrier optimization the whole bytes (8-bit chunks, not only single bits as presented on the figure above) are marked as potential roots sources. So in fact, such cross-generations reference can mark up to 2048 bytes (for 64-bit architectures: <em>256 bytes x 8 = 2048 bytes</em>) memory chunk as a potential GC roots source.</p>
<p>Every referenced object found this way is added to the list of objects still in use (if you still don&#8217;t know what are GC roots and still in use objects list, <a href="https://www.codejourney.net/2018/08/net-internals-05-garbage-collection-marking-collection-and-heaps-compaction/" target="_blank" rel="noopener">read the previous post now</a>).</p>
<h1>but&#8230; what about LOH?</h1>
<p>If you&#8217;re curious about Large Object Heap (LOH) in-depth memory organization, I recommend you reading <a href="https://blogs.msdn.microsoft.com/maoni/2016/05/31/large-object-heap-uncovered-from-an-old-msdn-article/" target="_blank" rel="noopener">this article by Maoni Stephens</a>. I can just mention that LOH has its own memory threshold which can be exceeded and it also triggers Gen 2 collection &#8211; from GC point-of-view, collection of objects allocated on LOH happens only during Gen 2 collection.</p>
<p>&nbsp;</p>
<h1>Summary</h1>
<p>We went through the concept of having SOH managed heap divided into 3 generations. By understanding how objects are promoted between generations and the implications of being a long-lived object we saw the potential harmful impact of static data on our application&#8217;s performance.</p>
<p>Another interesting thing we pointed out was the card table data structure used to solve cross-generations references issue.</p>
<p>Next week we&#8217;ll see more on unmanaged resources and objects&#8217; finalization.</p>
<p>Stay tuned! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>The post <a href="https://www.codejourney.net/net-internals-06-generational-garbage-collection/">[.NET Internals 06] Generational garbage collection</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/net-internals-06-generational-garbage-collection/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2741</post-id>	</item>
		<item>
		<title>[.NET Internals 05] Garbage collection: marking, collection and heaps compaction</title>
		<link>https://www.codejourney.net/net-internals-05-garbage-collection-marking-collection-and-heaps-compaction/</link>
					<comments>https://www.codejourney.net/net-internals-05-garbage-collection-marking-collection-and-heaps-compaction/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Wed, 22 Aug 2018 13:00:35 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[dotnet-internals]]></category>
		<guid isPermaLink="false">http://www.dsibinski.pl/?p=2712</guid>

					<description><![CDATA[<p>Today, in the next article from .NET Internals series on my blog, we&#8217;re going to investigate how the garbage collector (GC) actually releases the memory (which is its main purpose as could be read here), what is marking phase and how the managed heaps are compacted in order to optimize the process. We&#8217;ll also see&#8230;</p>
<p>The post <a href="https://www.codejourney.net/net-internals-05-garbage-collection-marking-collection-and-heaps-compaction/">[.NET Internals 05] Garbage collection: marking, collection and heaps compaction</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Today, in the next article from <a href="https://www.codejourney.net/tag/dotnet-internals/" target="_blank" rel="noopener">.NET Internals series</a> on my blog, we&#8217;re going to investigate how the garbage collector (GC) actually releases the memory (which is its main purpose as <a href="https://www.codejourney.net/2018/08/net-internals-04-what-is-garbage-collection-memory-allocation-in-net/" target="_blank" rel="noopener">could be read here</a>), what is <em>marking phase</em> and how the <a href="https://www.codejourney.net/2018/08/net-internals-02-stack-and-heap-net-data-structures/" target="_blank" rel="noopener">managed heaps</a> are <em>compacted</em> in order to optimize the process. We&#8217;ll also see when may the collection be triggered.<br />
<span id="more-2712"></span></p>
<h1>Finding objects to be garbage-collected</h1>
<p>As we <a href="https://www.codejourney.net/2018/08/net-internals-04-what-is-garbage-collection-memory-allocation-in-net/" target="_blank" rel="noopener">already know</a>, .NET doesn&#8217;t allow developers to directly allocate the objects on the heap. Instead, the only thing the programmer needs to do is to use the <span style="color: #ff6600;">new</span> keyword &#8211; framework takes care of all the rest (placing the object on the proper heap, initializing it etc.). After that, you can simply forget about your object, because it is released (collected) automatically by the garbage collector as soon as it&#8217;s not needed anymore. But how does the GC know which objects it can collect?</p>
<p>In principle, <strong>all the garbage collector does is looking for the allocated objects which aren&#8217;t referenced by anything</strong>, which means that such objects are no longer needed. This makes such objects ready to be collected (their memory can be released &#8211; marked as being possible to be used again).</p>
<p>There are several sources of references to objects allocated on the heap:</p>
<ul>
<li>stack (as we know from <a href="https://www.codejourney.net/2018/08/net-internals-02-stack-and-heap-net-data-structures/" target="_blank" rel="noopener">the 2nd post</a>),</li>
<li>global or static reference variables,</li>
<li>CPU registers,</li>
<li>interop references (.NET objects used in COM/API calls),</li>
<li>objects finalization references.</li>
</ul>
<h2>GC roots tree</h2>
<p>All above-listed sources are called <em>GC roots</em> (also referred to as <em>root references</em>). As objects referenced from any of the roots can reference another objects (for example a customer may reference its orders collection), all these nested references are represented as a tree (graph) for every .NET application. Such references tree may look as follows:</p>
<figure id="attachment_2713" aria-describedby="caption-attachment-2713" style="width: 658px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/GC_ReferncesTree.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2713" data-permalink="https://www.codejourney.net/net-internals-05-garbage-collection-marking-collection-and-heaps-compaction/gc_referncestree/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/GC_ReferncesTree.png?fit=658%2C228&amp;ssl=1" data-orig-size="658,228" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="GC_ReferncesTree" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/GC_ReferncesTree.png?fit=658%2C228&amp;ssl=1" class="wp-image-2713 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/GC_ReferncesTree.png?resize=658%2C228&#038;ssl=1" alt="" width="658" height="228" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/GC_ReferncesTree.png?w=658&amp;ssl=1 658w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/GC_ReferncesTree.png?resize=300%2C104&amp;ssl=1 300w" sizes="auto, (max-width: 658px) 100vw, 658px" /></a><figcaption id="caption-attachment-2713" class="wp-caption-text"><span style="font-size: 8pt;">Source: <em>Under the Hood of .NET memory Management</em></span></figcaption></figure>
<p>As you can see, GC root is present on the stack, pointing to <em>Customer</em> reference object. It contains an <em>ArrayList</em> collection of orders, which is referenced by <em>Customer</em> object. The collection itself also contains references to its elements, so the tree grows up.</p>
<p>Each root contains either a reference (address) to some object or null value.</p>
<h2>Unreachable (not used) objects</h2>
<p>The GC roots tree described above is used by garbage collector to know which objects are no longer needed. As we see, the graph contains all objects that are still in use (are referenced by something else).</p>
<p>GC uses this information the other way around &#8211;  generally the <strong>GC classifies all objects that are not reachable from any root (not present in the graph) as garbage</strong>. Such objects are then collected (the memory allocated for them is released) by the GC during its <em>collection cycles</em>, which will be described in details in the next posts in the series.</p>
<h1>Memory releasing (garbage collection)</h1>
<p>As mentioned, garbage collection is a process executed in cycles, which will be covered in the later articles, but the process itself contains two main steps:</p>
<ol>
<li><strong>Marking phase</strong> &#8211; finding which objects are still in use,</li>
<li><strong>Collection</strong> &#8211; actual collection process of not-anymore-used objects (including SOH compaction).</li>
</ol>
<p>Let&#8217;s see both phases in details.</p>
<h2>Marking phase</h2>
<p>When garbage collector runs its memory releasing process (referred to as &#8216;collection&#8217;), it needs to know which objects on the heap are still in use by the application &#8211; obviously, such objects cannot be collected.</p>
<p>In order to obtain this information, GC<strong> goes through the whole root references tree</strong> and for each GC root moves along all its reference tree (all objects that are referenced from the particular root) <strong>in order to <em>mark</em> each object in this tree as &#8220;still in use&#8221;</strong>. That&#8217;s why this integrated part of garbage collection process is called <em>marking phase</em>.</p>
<p>Marking is a recursive operation, because as we said before, roots reference some object, which references another object, which references another object&#8230;</p>
<p>so in order to make sure that every object in use is added to the &#8220;still in use&#8221; list (if it&#8217;s not there yet), this recursive marking is done as can be seen below:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91434616" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-gc_marking_pseudocode-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="GC_Marking_PseudoCode.cs content, created by dsibinski on 06:30PM on August 20, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="GC_Marking_PseudoCode.cs">
<tr>
<td id="file-gc_marking_pseudocode-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-gc_marking_pseudocode-cs-LC1" class="blob-code blob-code-inner js-file-line">  void Mark(objectRef o)</td>
</tr>
<tr>
<td id="file-gc_marking_pseudocode-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-gc_marking_pseudocode-cs-LC2" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-gc_marking_pseudocode-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-gc_marking_pseudocode-cs-LC3" class="blob-code blob-code-inner js-file-line">      if (!InUseList.Exists(o))</td>
</tr>
<tr>
<td id="file-gc_marking_pseudocode-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-gc_marking_pseudocode-cs-LC4" class="blob-code blob-code-inner js-file-line">      {</td>
</tr>
<tr>
<td id="file-gc_marking_pseudocode-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-gc_marking_pseudocode-cs-LC5" class="blob-code blob-code-inner js-file-line">          InUseList.Add(o);</td>
</tr>
<tr>
<td id="file-gc_marking_pseudocode-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-gc_marking_pseudocode-cs-LC6" class="blob-code blob-code-inner js-file-line">          List refs = GetAllChildReferences(o);</td>
</tr>
<tr>
<td id="file-gc_marking_pseudocode-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-gc_marking_pseudocode-cs-LC7" class="blob-code blob-code-inner js-file-line">          foreach (objectRef childRef in refs)</td>
</tr>
<tr>
<td id="file-gc_marking_pseudocode-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-gc_marking_pseudocode-cs-LC8" class="blob-code blob-code-inner js-file-line">          {</td>
</tr>
<tr>
<td id="file-gc_marking_pseudocode-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-gc_marking_pseudocode-cs-LC9" class="blob-code blob-code-inner js-file-line">              Mark(childRef);</td>
</tr>
<tr>
<td id="file-gc_marking_pseudocode-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-gc_marking_pseudocode-cs-LC10" class="blob-code blob-code-inner js-file-line">          }</td>
</tr>
<tr>
<td id="file-gc_marking_pseudocode-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-gc_marking_pseudocode-cs-LC11" class="blob-code blob-code-inner js-file-line">      }</td>
</tr>
<tr>
<td id="file-gc_marking_pseudocode-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-gc_marking_pseudocode-cs-LC12" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
<tr>
<td id="file-gc_marking_pseudocode-cs-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
<td id="file-gc_marking_pseudocode-cs-LC13" class="blob-code blob-code-inner js-file-line"> // source: Under the Hood of .NET Memory Management</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/894cc10e61c3d6eca437e5690353b010/raw/f1805b55958269fb920fc90812e9139785760b39/GC_Marking_PseudoCode.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/894cc10e61c3d6eca437e5690353b010#file-gc_marking_pseudocode-cs" class="Link--inTextBlock"><br />
          GC_Marking_PseudoCode.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>Let&#8217;s now see how it fits into the actual collection operation.</p>
<h2>Collection</h2>
<p>The actual collection process, including previously-examined marking phase, can be pictured with the following pseudo-code:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91434554" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-gc_collect_pseudocode-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="GC_Collect_PseudoCode.cs content, created by dsibinski on 06:26PM on August 20, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="GC_Collect_PseudoCode.cs">
<tr>
<td id="file-gc_collect_pseudocode-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-gc_collect_pseudocode-cs-LC1" class="blob-code blob-code-inner js-file-line">  void Collect()</td>
</tr>
<tr>
<td id="file-gc_collect_pseudocode-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-gc_collect_pseudocode-cs-LC2" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-gc_collect_pseudocode-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-gc_collect_pseudocode-cs-LC3" class="blob-code blob-code-inner js-file-line">      List gcRoots = GetAllGCRoots();</td>
</tr>
<tr>
<td id="file-gc_collect_pseudocode-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-gc_collect_pseudocode-cs-LC4" class="blob-code blob-code-inner js-file-line">      foreach (objectRef root in gcRoots)</td>
</tr>
<tr>
<td id="file-gc_collect_pseudocode-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-gc_collect_pseudocode-cs-LC5" class="blob-code blob-code-inner js-file-line">      {</td>
</tr>
<tr>
<td id="file-gc_collect_pseudocode-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-gc_collect_pseudocode-cs-LC6" class="blob-code blob-code-inner js-file-line">          Mark(root);</td>
</tr>
<tr>
<td id="file-gc_collect_pseudocode-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-gc_collect_pseudocode-cs-LC7" class="blob-code blob-code-inner js-file-line">      }</td>
</tr>
<tr>
<td id="file-gc_collect_pseudocode-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-gc_collect_pseudocode-cs-LC8" class="blob-code blob-code-inner js-file-line">      Cleanup();</td>
</tr>
<tr>
<td id="file-gc_collect_pseudocode-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-gc_collect_pseudocode-cs-LC9" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
<tr>
<td id="file-gc_collect_pseudocode-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-gc_collect_pseudocode-cs-LC10" class="blob-code blob-code-inner js-file-line">// source: Under the Hood of .NET Memory Management</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/7902dcca5400b36b0751ca69ed8124e5/raw/e4d581bdd45849ed14be3db1c75a37e73c4b7850/GC_Collect_PseudoCode.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/7902dcca5400b36b0751ca69ed8124e5#file-gc_collect_pseudocode-cs" class="Link--inTextBlock"><br />
          GC_Collect_PseudoCode.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>First of all, GC gets a list of all GC roots in the application (the list is maintained by JIT compiler and the runtime). Then it needs to iterate through each root and perform marking operation on it. Knowing that marking is a recursive operation, after this phase is finished, GC can be sure that all objects that have any root reference (either direct one or being pointed to by another objects) are added to the list of objects in use.</p>
<p>Next step is the actual memory releasing process of not used objects, represented as a call to <span style="color: #ff6600;">Cleanup()</span> method on the listing above. Memory cleanup itself is a very simple process &#8211; it&#8217;s just marking a particular memory block(s) as free (not used). There&#8217;s no overwriting of memory or anything like that <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> (except &#8216;side overwriting&#8217; which happens during heaps compaction &#8211; described below). Just simple boolean-like terminology is used for memory blocks &#8211; used (1) or not used (0). It works that simple for LOH , but collection on SOH (still don&#8217;t know what are <em>LOH</em> and <em>SOH</em>? Go and <a href="https://www.codejourney.net/2018/08/net-internals-02-stack-and-heap-net-data-structures/" target="_blank" rel="noopener">read here</a> quickly!) also involves the <em>compaction</em> process. Let&#8217;s see what that is.</p>
<h2>Heaps compaction</h2>
<p>As we know from <a href="https://www.codejourney.net/2018/07/net-internals-01-basics-of-memory-structure/" target="_blank" rel="noopener">the first post</a>, memory on the managed heaps can get fragmented, leaving holes of not used memory between live objects. That&#8217;s why the garbage collection for SOH process involves <strong><em>compaction</em>, which is a process of removing the memory holes on the heap</strong>. It&#8217;s often referred to as a<em> Copy Collection</em> process, because it&#8217;s based on finding the dead objects or memory holes (it&#8217;s actually the same &#8211; holes of the memory that are not used by anything, present in-between live objects) and overwriting these holes with the live objects allocated later (next) on the heap &#8211; by copying chunks of live objects &#8216;down in the heap&#8217;.</p>
<p>The <strong>result of the compaction process</strong> is the contiguous SOH, where <strong>objects are allocated on top of each other with no or minimal possible number of memory holes</strong>.</p>
<p>Finally, addresses to the objects stored in reference variables are updated in order to point to the correct, new places in the memory occupied by particular object.</p>
<p>The best gain we get from the compaction is that the SOH is not fragmented, so the memory can be used efficiently. On the other hand it requires some CPU time, which may have some impact on our application&#8217;s performance.</p>
<p>By default, LOH is not compacted because of the size of objects stored on it (&gt;85 kilobytes). Copying chunks of such objects would take too much time. Instead, used space and memory holes on the LOH are tracked and the allocation algorithm is adjusted to try to reserve the memory for new objects in the optimal way (by finding the best possible free slots on the fragmented heap).</p>
<p>What&#8217;s worth noticing is that starting from .NET Framework 4.5.1, LOH compaction can be enabled on demand by using <a href="https://docs.microsoft.com/en-us/dotnet/api/system.runtime.gcsettings.largeobjectheapcompactionmode?view=netframework-4.7.2" target="_blank" rel="noopener">GCSettings.LargeObjectHeapCompactionMode property</a>.</p>
<h1>When does the GC run?</h1>
<p>It can be stated that GC works in a non-deterministic manner. It runs on a separate thread when one of the following conditions becomes true:</p>
<ul>
<li> the OS sends low memory notification,</li>
<li>the memory used by the objects on the managed heap exceeds some defined threshold (which is adjusted dynamically at runtime, based on current allocations),</li>
<li><span style="color: #ff6600;">GC.Collect()</span> method is called in the code.</li>
</ul>
<p>If you see <span style="color: #ff6600;">GC.Collect()</span> directly used in code, in almost every case it means that there&#8217;s something wrong with the application&#8217;s implementation. Several great Microsoft engineers and open-source contributors have worked on automatic garbage collection in order to not trigger it manually <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>The exceptions for this rule I&#8217;d accept are maybe some gaming implementations, in which you work with huge objects and sometimes you&#8217;d like to affect the way when these objects&#8217; memory is cleaned-up or usage in debugging &#8211; most of memory profilers (like <a href="https://www.jetbrains.com/dotmemory/" target="_blank" rel="noopener">dotMemory</a> or <a href="https://www.red-gate.com/products/dotnet-development/ants-memory-profiler/index" target="_blank" rel="noopener">ANTS Memory Profiler</a>) force the collection before the memory snapshot is done by the user. This is reasonable, because when debugging memory leaks or issues you wanna see which objects remain allocated after GC does its cleanup.</p>
<p>What&#8217;s also worth mentioning is that when the garbage collection is run, all threads are stopped by default, except the thread in which the collection was triggered. However, this can be configured by changing the GC&#8217;s settings to work in workstation or server mode, as well as making it run concurrently or in the background. There are different use cases in which each settings combination should be used &#8211; you can find more details about it <a href="https://blogs.msdn.microsoft.com/seteplia/2017/01/05/understanding-different-gc-modes-with-concurrency-visualizer/" target="_blank" rel="noopener">here</a> and <a href="https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/fundamentals" target="_blank" rel="noopener">here</a>.</p>
<h1>Summary</h1>
<p>Today we&#8217;ve covered the main blocks from which the garbage collection process in .NET is built. We went through marking phase, then the actual collection process &#8211; also including heaps compaction. We learnt how the GC roots tree is built and how garbage collector knows which objects it can clean-up during its cycle. We also listed cases in which the collection can be triggered.</p>
<p>In the next post we&#8217;ll examine a very interesting concept &#8211; generational garbage collection.</p>
<p>See ya next week! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>The post <a href="https://www.codejourney.net/net-internals-05-garbage-collection-marking-collection-and-heaps-compaction/">[.NET Internals 05] Garbage collection: marking, collection and heaps compaction</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/net-internals-05-garbage-collection-marking-collection-and-heaps-compaction/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2712</post-id>	</item>
		<item>
		<title>[.NET Internals 04] What is Garbage Collection? Memory allocation in .NET</title>
		<link>https://www.codejourney.net/net-internals-04-what-is-garbage-collection-memory-allocation-in-net/</link>
					<comments>https://www.codejourney.net/net-internals-04-what-is-garbage-collection-memory-allocation-in-net/#respond</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Wed, 15 Aug 2018 06:00:59 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[dotnet-internals]]></category>
		<guid isPermaLink="false">http://www.dsibinski.pl/?p=2670</guid>

					<description><![CDATA[<p>In the next, 4th post from .NET Internals series, we&#8217;re going to meet a new friend called Garbage Collector, discuss this guy&#8217;s main responsibilities and see what is memory allocation in .NET applications and how it works. Ready? Let&#8217;s start then! 😉 What (or who) is Garbage Collection (Collector)? As you could read in the previous&#8230;</p>
<p>The post <a href="https://www.codejourney.net/net-internals-04-what-is-garbage-collection-memory-allocation-in-net/">[.NET Internals 04] What is Garbage Collection? Memory allocation in .NET</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In the next, 4th post from <a href="https://www.codejourney.net/tag/dotnet-internals/" target="_blank" rel="noopener">.NET Internals series</a>, we&#8217;re going to meet a new friend called <em>Garbage Collector</em>, discuss this guy&#8217;s main responsibilities and see what is memory allocation in .NET applications and how it works.</p>
<p>Ready? Let&#8217;s start then! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /><br />
<span id="more-2670"></span></p>
<h1>What (or who) is Garbage Collection (Collector)?</h1>
<p>As you could read in the <a href="https://www.codejourney.net/tag/dotnet-internals/" target="_blank" rel="noopener">previous posts</a> on internal details of .NET,  there are a lot of conditions and assumption of memory organization in the framework. Data is stored <a href="https://www.codejourney.net/2018/08/net-internals-02-stack-and-heap-net-data-structures/" target="_blank" rel="noopener">on the proper structures</a>, sometimes <a href="https://www.codejourney.net/2018/08/net-internals-03-boxing-and-unboxing/" target="_blank" rel="noopener">boxed and unboxed</a>, but what&#8217;s the best about it all is that <strong>it&#8217;s almost completely invisible for us &#8211; developers</strong>.</p>
<p>In fact, providing this <em>invisibility </em>is a goal of <em>Garbage Collector</em> <em>(GC)</em>. It should become our close friend (it&#8217;s not that scary as you could have heard &#8211; we&#8217;ll see that soon <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> ), because this <strong>automatic memory manager</strong> does a lot of stuff for us, including:</p>
<ul>
<li>allowing us to write code without having to release memory (still remember <a href="https://www.codejourney.net/2018/07/net-internals-01-basics-of-memory-structure/" target="_blank" rel="noopener">the meme about C++?</a>),</li>
<li>performing heap allocations in an efficient way,</li>
<li>reclaiming the objects that are no longer used and clearing their memory,</li>
<li>ensuring that every new managed object gets clean content to begin with, so there is no work to be done in an object&#8217;s constructor to allocate the memory for all its members,</li>
<li>providing memory safety, so one object cannot use the memory reserved for another object.
</li>
</ul>
<p>The term &#8216;garbage collection&#8217; was firstly used in <a href="https://en.wikipedia.org/wiki/Lisp_(programming_language)" target="_blank" rel="noopener">LISP programming language</a> in 1959 and since then it represents the concept of automatic memory management in programming languages and frameworks.</p>
<h1>Does GC allocate or deallocate the memory?</h1>
<p>There&#8217;s often this confusion between allocating and deallocating the memory &#8211; what is actually responsible for that? In principle, <strong>the goal of garbage collector is to</strong> <strong>deallocate the memory</strong> &#8211; as its name suggests, it <em>collects</em> (frees, reclaims) the <em>garbage</em> (not-anymore-needed objects).</p>
<p>On the other hand, when there&#8217;s any memory allocation request sent by an application, such query is transferred to CLR, which is actually responsible for allocating the memory. However, as we&#8217;ll see in the coming posts, the deallocation of memory (which is much more complex process that allocating it) can be triggered on various conditions and it can happen that <strong>allocation of the memory requires deallocation to be performed first</strong>. It doesn&#8217;t mean that this is a sequence of events (i.e. before allocation the deallocation is performed), but that the number of allocations done by the CLR can affect the way and frequency of garbage collections (we&#8217;d like to have available memory when an allocation is to be done).</p>
<p>That&#8217;s how the CLR &#8216;asks&#8217; GC for help (or &#8216;communicates with GC&#8217; by notifying it about allocations) in actually allocating the memory (for instance by making GC running a collection or heap compaction process more frequently). Because of that reason, it&#8217;s usually simplified that garbage collector handles both allocation and deallocation of memory.</p>
<p>As we&#8217;ll see below, <strong>allocation of memory is as simple as <em>1 + 2 = 3</em></strong> <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> &#8211; continue reading to get to know why!</p>
<script>(function() {
	window.mc4wp = window.mc4wp || {
		listeners: [],
		forms: {
			on: function(evt, cb) {
				window.mc4wp.listeners.push(
					{
						event   : evt,
						callback: cb
					}
				);
			}
		}
	}
})();
</script><!-- Mailchimp for WordPress v4.12.2 - https://wordpress.org/plugins/mailchimp-for-wp/ --><form id="mc4wp-form-4" class="mc4wp-form mc4wp-form-2612" method="post" data-id="2612" data-name="Download a free guide form" ><div class="mc4wp-form-fields"><table bgcolor="#f2f6f5"><tr><td> <p><p>
    <label>
<h1 style="">
  <center>GET A FREE GUIDE <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f381.png" alt="🎁" class="wp-smiley" style="height: 1em; max-height: 1em;" /></center>
      </h1>        
      <h2 style="font-family: Helvetica">
        <center>16 STEPS TO BECOME <br/>.NET FULL STACK WEB DEVELOPER </br>IN 2025</center>
      </h2>
</p>
  <center><div>
	<input type="email" name="EMAIL" placeholder="Email address" required />
    <p>
    <input type="text" name="FNAME" placeholder="Your name"
    required="">
  </p>
  </div>
    <center>

	<center><input type="submit" value="DOWNLOAD THE FREE GUIDE" style="color: #7b1fa2; font-weight:bold; font-size: 20px" /></center>
<p style="font-size: 12px; font-style: italic;">After you sign up, I may be sending you some emails with additional free content from time to time.
<br/>No spam, only awesome stuff</p>
</p></td></tr></table>

</div><label style="display: none !important;">Leave this field empty if you're human: <input type="text" name="_mc4wp_honeypot" value="" tabindex="-1" autocomplete="off" /></label><input type="hidden" name="_mc4wp_timestamp" value="1778077250" /><input type="hidden" name="_mc4wp_form_id" value="2612" /><input type="hidden" name="_mc4wp_form_element_id" value="mc4wp-form-4" /><div class="mc4wp-response"></div></form><!-- / Mailchimp for WordPress Plugin -->
<h1>Memory allocation in .NET</h1>
<p>As we read in the <a href="https://www.codejourney.net/2018/07/net-internals-01-basics-of-memory-structure/" target="_blank" rel="noopener">first post of the series</a>, each process has its own virtual address space. Garbage collector is responsible for allocating the memory on the managed heaps (more about heaps <a href="https://www.codejourney.net/2018/08/net-internals-02-stack-and-heap-net-data-structures/" target="_blank" rel="noopener">here</a>) created in this process&#8217;s space. It means that <strong>garbage collector only takes care of reference type objects</strong>.</p>
<p>Value types are stored on the stack in LIFO order and their memory is reclaimed as soon as the method in which these value types are defined exits. It would make no sense if GC had to manage these theoretically simple and (in a perfect world) locally declared variables.</p>
<h2>Next object pointer</h2>
<p>To make it simple, as soon as managed heap is created, it contains a <em>pointer</em> to the memory address where the next object will be allocated. This pointer is simply a number and is referred to as <em>next object pointer</em>. Initially, its value is set to managed heap&#8217;s base address:</p>
<p>&nbsp;</p>
<figure id="attachment_2684" aria-describedby="caption-attachment-2684" style="width: 391px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/NOP.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2684" data-permalink="https://www.codejourney.net/net-internals-04-what-is-garbage-collection-memory-allocation-in-net/nop/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/NOP.png?fit=391%2C320&amp;ssl=1" data-orig-size="391,320" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="NOP" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/NOP.png?fit=391%2C320&amp;ssl=1" class="wp-image-2684 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/NOP.png?resize=391%2C320&#038;ssl=1" alt="" width="391" height="320" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/NOP.png?w=391&amp;ssl=1 391w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/NOP.png?resize=300%2C246&amp;ssl=1 300w" sizes="auto, (max-width: 391px) 100vw, 391px" /></a><figcaption id="caption-attachment-2684" class="wp-caption-text"><span style="font-size: 8pt;">Managed heap and next object pointer</span></figcaption></figure>
<p>As soon as the first-ever reference object is to be allocated on this particular heap, the memory is allocated in the place where the next object pointer currently points to. State of the heap after first allocation would be something like that:</p>
<figure id="attachment_2685" aria-describedby="caption-attachment-2685" style="width: 395px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/NOP_After1stAllocation.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2685" data-permalink="https://www.codejourney.net/net-internals-04-what-is-garbage-collection-memory-allocation-in-net/nop_after1stallocation/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/NOP_After1stAllocation.png?fit=395%2C318&amp;ssl=1" data-orig-size="395,318" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="NOP_After1stAllocation" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/NOP_After1stAllocation.png?fit=395%2C318&amp;ssl=1" class="wp-image-2685 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/NOP_After1stAllocation.png?resize=395%2C318&#038;ssl=1" alt="" width="395" height="318" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/NOP_After1stAllocation.png?w=395&amp;ssl=1 395w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/NOP_After1stAllocation.png?resize=300%2C242&amp;ssl=1 300w" sizes="auto, (max-width: 395px) 100vw, 395px" /></a><figcaption id="caption-attachment-2685" class="wp-caption-text"><span style="font-size: 8pt;">Managed heap and next object pointer after allocation</span></figcaption></figure>
<p>As presented above, the next object pointer is moved to the address just after the allocated object. It ensures that there are no unnecessary memory gaps on the heap.</p>
<h2>Complexity of memory allocation</h2>
<p>In reality, the next object pointer&#8217;s value is a number in hexadecimal format (e.g. <em>0xF7279</em>). When a new allocation is to be made, <strong>the only operation to perform is an addition operation</strong>. It is known how much space is needed for the new object (more details in the next section), so in order to reserve the proper memory chunk, number of bytes necessary for a new object is added to the next object pointer&#8217;s current value.</p>
<p>This is how the reservation of managed memory works. Because of that it can be said that allocating the memory for reference types is almost as fast as allocating variables on the stack.</p>
<p>If you&#8217;d like to see how you can check the memory address of an object, I recommend <a href="https://gooroo.io/GoorooTHINK/Article/17038/Pointers-and-Unsafe-Code-in-C-everything-you-need-to-know/25066" target="_blank" rel="noopener">checking this article</a>.</p>
<h1>How is an object&#8217;s size calculated?</h1>
<p>In the comments under <a href="https://www.codejourney.net/2018/08/net-internals-03-boxing-and-unboxing" target="_blank" rel="noopener">the previous post</a>, Jelena asked for explanation on how the size of an object is calculated. Here it comes <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>As we all know <a href="https://www.codejourney.net/2018/08/net-internals-02-stack-and-heap-net-data-structures/" target="_blank" rel="noopener">from the second post</a>, object is sometimes allocated on the Small Object Heap (SOH) or Large Object Heap (LOH) depending on its size. For that reason before the allocation is made, the object&#8217;s size must be determined. How is this size calculated then?</p>
<p>It would make things easy to assume that size of an object is everything it contains (also other objects&#8217; sizes). In reality, it&#8217;s not counted this way. Objects contained in another objects are allocated separately on the heap, so their actual sizes are not included in the parent object&#8217;s size.</p>
<p>Very good example is given in Chris Farrell&#8217;s and Nick Harrison&#8217;s book &#8211; <em>Under the Hood of .NET Memory Management</em>. If we consider the following code:</p>
<p><style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91326246" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-string_array_allocation-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="string_array_allocation.cs content, created by dsibinski on 05:07PM on August 14, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="string_array_allocation.cs">
<tr>
<td id="file-string_array_allocation-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-string_array_allocation-cs-LC1" class="blob-code blob-code-inner js-file-line">  class MyClass</td>
</tr>
<tr>
<td id="file-string_array_allocation-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-string_array_allocation-cs-LC2" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-string_array_allocation-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-string_array_allocation-cs-LC3" class="blob-code blob-code-inner js-file-line">      string Test=&quot;Hello world Wazzup!&quot;; // 19 characters</td>
</tr>
<tr>
<td id="file-string_array_allocation-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-string_array_allocation-cs-LC4" class="blob-code blob-code-inner js-file-line">      byte[] data=new byte[86000]; // 86000 bytes (&gt;85K &#8211; goes on LOH)</td>
</tr>
<tr>
<td id="file-string_array_allocation-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-string_array_allocation-cs-LC5" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/e209c3fb74bd5f940d2c44bc140582a5/raw/8a719975e8f847a8ffc863d8c4dcfdfedf6b0368/string_array_allocation.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/e209c3fb74bd5f940d2c44bc140582a5#file-string_array_allocation-cs" class="Link--inTextBlock"><br />
          string_array_allocation.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>That&#8217;s how the heaps&#8217; state looks like as soon as as instance of <span style="color: #ff6600;">MyClass</span> is created:</p>
<figure id="attachment_2686" aria-describedby="caption-attachment-2686" style="width: 525px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringArray_AllocationState.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2686" data-permalink="https://www.codejourney.net/net-internals-04-what-is-garbage-collection-memory-allocation-in-net/stringarray_allocationstate/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringArray_AllocationState.png?fit=525%2C310&amp;ssl=1" data-orig-size="525,310" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="StringArray_AllocationState" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringArray_AllocationState.png?fit=525%2C310&amp;ssl=1" class="wp-image-2686 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringArray_AllocationState.png?resize=525%2C310&#038;ssl=1" alt="" width="525" height="310" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringArray_AllocationState.png?w=525&amp;ssl=1 525w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringArray_AllocationState.png?resize=300%2C177&amp;ssl=1 300w" sizes="auto, (max-width: 525px) 100vw, 525px" /></a><figcaption id="caption-attachment-2686" class="wp-caption-text"><span style="font-size: 8pt;">Source: <em>Under the Hood of .NET Memory Management</em></span></figcaption></figure>
<p>The size of <span style="color: #ff6600;">MyClass</span> object instance will include:</p>
<ul>
<li>general class stuff (e.g. some metadata &#8211; you can check it yourself in IL code with ILSpy as we did with <a href="https://www.codejourney.net/2018/08/net-internals-03-boxing-and-unboxing/" target="_blank" rel="noopener">boxing and unboxing</a>),</li>
<li>memory required to store the pointers (memory addresses) to the string and bytes array.</li>
</ul>
<p><span style="color: #ff6600;">string Test</span> will be allocated on the SOH, and <span style="color: #ff6600;">byte[] data</span> will be allocated on the LOH (it&#8217;s more than 85K).</p>
<p>In general, the size of an object is calculated by adding sizes of:</p>
<ul>
<li>general class data,</li>
<li>pointers (for reference types class members) containing only addresses in memory (hexadecimal numbers),</li>
<li>value types (for value types class members) &#8211; more details <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/sizeof" target="_blank" rel="noopener">here</a>.</li>
</ul>
<h1>Summary</h1>
<p>I hope this post makes the role of garbage collector a bit more clear for you. We&#8217;ve also seen how easy the memory allocation is and what&#8217;s the general way of calculating an object&#8217;s size.</p>
<p>Even we don&#8217;t perform the actual allocations ourselves manually and may think like this guy:</p>
<figure id="attachment_2691" aria-describedby="caption-attachment-2691" style="width: 500px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/GC_Meme.jpg?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2691" data-permalink="https://www.codejourney.net/net-internals-04-what-is-garbage-collection-memory-allocation-in-net/gc_meme/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/GC_Meme.jpg?fit=500%2C344&amp;ssl=1" data-orig-size="500,344" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="GC_Meme" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/GC_Meme.jpg?fit=500%2C344&amp;ssl=1" class="wp-image-2691 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/GC_Meme.jpg?resize=500%2C344&#038;ssl=1" alt="" width="500" height="344" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/GC_Meme.jpg?w=500&amp;ssl=1 500w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/GC_Meme.jpg?resize=300%2C206&amp;ssl=1 300w" sizes="auto, (max-width: 500px) 100vw, 500px" /></a><figcaption id="caption-attachment-2691" class="wp-caption-text"><span style="font-size: 8pt;">Source: <a href="https://twitter.com/ben_a_adams/status/895065527197982720" target="_blank" rel="noopener">this Ben Adams&#8217;s tweet</a></span></figcaption></figure>
<p>We&#8217;ll see if that&#8217;s true next week, when we&#8217;ll dig into more complex topic, the real purpose of the GC &#8211; releasing the memory!</p>
<p>Stay tuned!</p>
<p>The post <a href="https://www.codejourney.net/net-internals-04-what-is-garbage-collection-memory-allocation-in-net/">[.NET Internals 04] What is Garbage Collection? Memory allocation in .NET</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/net-internals-04-what-is-garbage-collection-memory-allocation-in-net/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2670</post-id>	</item>
		<item>
		<title>[.NET Internals 03] Boxing and unboxing</title>
		<link>https://www.codejourney.net/net-internals-03-boxing-and-unboxing/</link>
					<comments>https://www.codejourney.net/net-internals-03-boxing-and-unboxing/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Wed, 08 Aug 2018 06:04:05 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[dotnet-internals]]></category>
		<guid isPermaLink="false">http://www.dsibinski.pl/?p=2622</guid>

					<description><![CDATA[<p>As we are already familiar with the basics of memory and data structures used by .NET applications, in this third post from .NET Internals series we&#8217;re going to dig into boxing and unboxing and their performance implications. What is boxing and unboxing? In the previous post we learnt what are value and reference types and got&#8230;</p>
<p>The post <a href="https://www.codejourney.net/net-internals-03-boxing-and-unboxing/">[.NET Internals 03] Boxing and unboxing</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>As we are already familiar with the <a href="https://www.codejourney.net/2018/07/net-internals-01-basics-of-memory-structure/" target="_blank" rel="noopener">basics of memory</a> and <a href="https://www.codejourney.net/2018/08/net-internals-02-stack-and-heap-net-data-structures/" target="_blank" rel="noopener">data structures</a> used by .NET applications, in this third post from <a href="https://www.codejourney.net/tag/dotnet-internals/" target="_blank" rel="noopener">.NET Internals series</a> we&#8217;re going to dig into <em>boxing</em> and <em>unboxing</em> and their performance implications.<br />
<span id="more-2622"></span></p>
<h1>What is boxing and unboxing?</h1>
<p>In the <a href="https://www.codejourney.net/2018/08/net-internals-02-stack-and-heap-net-data-structures/" target="_blank" rel="noopener">previous post</a> we learnt what are value and reference types and got to know that the former are stored on the stack, whereas the latter are stored on the managed heap. So why should we care? Isn&#8217;t it .NET runtime which correctly manages these data structures and what&#8217;s stored on them so we don&#8217;t need to worry about that?</p>
</p>
<p>In fact, no. What&#8217;s crucial to know and understand are the implications of <strong>moving data from the stack to the heap</strong> and otherwise.</p>
</p>
<p><span style="text-decoration: underline;">Remember</span>:</p>
<ul>
<li>when any <strong>value type</strong> variable is <strong>assigned to a reference type</strong> variable, <strong>data is moved from the stack to the heap</strong> and this is called <strong><span style="text-decoration: underline;">boxing</span>,</strong></li>
<li>when any <strong>reference type</strong> variable is <strong>assigned to a value type</strong> variable, <strong>data is moved from the heap to the stack</strong> and this is called <strong><span style="text-decoration: underline;">unboxing</span>. </strong>
</p>
</li>
</ul>
<p><a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/boxing-and-unboxing" target="_blank" rel="noopener">Microsoft Docs examples</a> illustrate these actions very well.</p>
<p>Consider the following example of boxing:</p>
<style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91148841" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-boxing_example-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="Boxing_example.cs content, created by dsibinski on 07:52PM on August 04, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="Boxing_example.cs">
<tr>
<td id="file-boxing_example-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-boxing_example-cs-LC1" class="blob-code blob-code-inner js-file-line">int i = 123;</td>
</tr>
<tr>
<td id="file-boxing_example-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-boxing_example-cs-LC2" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-boxing_example-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-boxing_example-cs-LC3" class="blob-code blob-code-inner js-file-line">// Boxing &#8211; copying the value of i into object o.</td>
</tr>
<tr>
<td id="file-boxing_example-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-boxing_example-cs-LC4" class="blob-code blob-code-inner js-file-line">object o = i;  </td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/ce84dd9c2feeae51bba1a35e438cf2ac/raw/6b67a8f30617d2ac6377025a01d2fee30834866f/Boxing_example.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/ce84dd9c2feeae51bba1a35e438cf2ac#file-boxing_example-cs" class="Link--inTextBlock"><br />
          Boxing_example.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>and the memory state as it executes:</p>
<figure id="attachment_2625" aria-describedby="caption-attachment-2625" style="width: 228px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Boxing_Example.gif?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2625" data-permalink="https://www.codejourney.net/net-internals-03-boxing-and-unboxing/boxing_example/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Boxing_Example.gif?fit=228%2C148&amp;ssl=1" data-orig-size="228,148" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Boxing_Example" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Boxing_Example.gif?fit=228%2C148&amp;ssl=1" class="wp-image-2625 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Boxing_Example.gif?resize=228%2C148&#038;ssl=1" alt="" width="228" height="148" /></a><figcaption id="caption-attachment-2625" class="wp-caption-text"><span style="font-size: 8pt;">Boxing, <a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/boxing-and-unboxing" target="_blank" rel="noopener">source</a></span></figcaption></figure>
<p>In order to store &#8220;123&#8221; value in an <span style="color: #ff6600;">object</span>, the &#8220;box&#8221; is created on the heap and the value is copied inside it.</p>
</p>
<p>On the other hand, when unboxing happens:</p>
<style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91148939" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-unboxing_example-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="Unboxing_Example.cs content, created by dsibinski on 08:00PM on August 04, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="Unboxing_Example.cs">
<tr>
<td id="file-unboxing_example-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-unboxing_example-cs-LC1" class="blob-code blob-code-inner js-file-line">int i = 123;      // &quot;i&quot; is a value type</td>
</tr>
<tr>
<td id="file-unboxing_example-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-unboxing_example-cs-LC2" class="blob-code blob-code-inner js-file-line">object o = i;     // boxing &quot;i&quot; into &quot;o&quot;</td>
</tr>
<tr>
<td id="file-unboxing_example-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-unboxing_example-cs-LC3" class="blob-code blob-code-inner js-file-line">int j = (int)o;   // unboxing &quot;o&quot; into &quot;j&quot;</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/7ec30a97fb93a7cffbb6e911979f8cbe/raw/36c03294f1506720f87e58379174636088a0e794/Unboxing_Example.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/7ec30a97fb93a7cffbb6e911979f8cbe#file-unboxing_example-cs" class="Link--inTextBlock"><br />
          Unboxing_Example.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>that&#8217;s how stack&#8217;s and heap&#8217;s content changes:</p>
<figure id="attachment_2631" aria-describedby="caption-attachment-2631" style="width: 228px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Unboxing_Example.gif?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2631" data-permalink="https://www.codejourney.net/net-internals-03-boxing-and-unboxing/unboxing_example/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Unboxing_Example.gif?fit=228%2C215&amp;ssl=1" data-orig-size="228,215" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Unboxing_Example" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Unboxing_Example.gif?fit=228%2C215&amp;ssl=1" class="wp-image-2631 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/Unboxing_Example.gif?resize=228%2C215&#038;ssl=1" alt="" width="228" height="215" /></a><figcaption id="caption-attachment-2631" class="wp-caption-text">Unboxing, <a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/boxing-and-unboxing" target="_blank" rel="noopener">source</a></figcaption></figure>
<p>Value &#8220;123&#8221; is taken out of the &#8220;box&#8221; and placed back on the stack.</p>
</p>
<p>Notice that when <span style="color: #ff6600;">i</span> value type is boxed into object <span style="color: #ff9900;"><span style="color: #ff6600;">o</span><span style="color: #000000;">,</span> <span style="color: #000000;">there&#8217;s a reference stored on the stack and the actual memory is allocated on the heap (as for all reference types). As soon as the unboxing happens, the real data being on the heap must be copied to the stack (variable <span style="color: #ff6600;">j</span>). In both cases our goal is to deal with the same value (123).</span></span></p>
</p>
<p>As you can imagine, these operations produce some additional cost and affect the performance, which we&#8217;ll discuss in a moment.</p>
<h1>Let&#8217;s see some IL</h1>
<p>When analyzing such performance or memory management aspects in our code (C# in that case), it&#8217;s often worth to see how the <a href="https://en.wikipedia.org/wiki/Common_Intermediate_Language" target="_blank" rel="noopener">Intermediate Language</a> (IL) looks like.</p>
</p>
<p>We haven&#8217;t covered this concept yet, but as you probably know when C# code is compiled into DLL or EXE, these output files actually contain the IL code, which is later JIT-compiled and executed by the virtual machine (more details <a href="https://www.codejourney.net/2018/10/net-internals-10-application-execution-model/" data-wplink-edit="true">here</a>). The .NET runtime must somehow know whether is should box or unbox the particular variable, as it requires some special memory allocation actions to be taken.</p>
</p>
<p>Let&#8217;s create some simple .NET Console Application with the following code in its <span style="color: #ff6600;">Main</span> method:</p>
<style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91212016" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-boxingunboxing_sample-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="BoxingUnboxing_sample.cs content, created by dsibinski on 04:20AM on August 08, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="BoxingUnboxing_sample.cs">
<tr>
<td id="file-boxingunboxing_sample-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-boxingunboxing_sample-cs-LC1" class="blob-code blob-code-inner js-file-line">  namespace BoxingUnboxingTest</td>
</tr>
<tr>
<td id="file-boxingunboxing_sample-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-boxingunboxing_sample-cs-LC2" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-boxingunboxing_sample-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-boxingunboxing_sample-cs-LC3" class="blob-code blob-code-inner js-file-line">      class Program</td>
</tr>
<tr>
<td id="file-boxingunboxing_sample-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-boxingunboxing_sample-cs-LC4" class="blob-code blob-code-inner js-file-line">      {</td>
</tr>
<tr>
<td id="file-boxingunboxing_sample-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-boxingunboxing_sample-cs-LC5" class="blob-code blob-code-inner js-file-line">          static void Main(string[] args)</td>
</tr>
<tr>
<td id="file-boxingunboxing_sample-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-boxingunboxing_sample-cs-LC6" class="blob-code blob-code-inner js-file-line">          {</td>
</tr>
<tr>
<td id="file-boxingunboxing_sample-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-boxingunboxing_sample-cs-LC7" class="blob-code blob-code-inner js-file-line">              int a = 5;</td>
</tr>
<tr>
<td id="file-boxingunboxing_sample-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-boxingunboxing_sample-cs-LC8" class="blob-code blob-code-inner js-file-line">              object o = a;</td>
</tr>
<tr>
<td id="file-boxingunboxing_sample-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-boxingunboxing_sample-cs-LC9" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="file-boxingunboxing_sample-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-boxingunboxing_sample-cs-LC10" class="blob-code blob-code-inner js-file-line">              int b = (int)o;</td>
</tr>
<tr>
<td id="file-boxingunboxing_sample-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-boxingunboxing_sample-cs-LC11" class="blob-code blob-code-inner js-file-line">          }</td>
</tr>
<tr>
<td id="file-boxingunboxing_sample-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-boxingunboxing_sample-cs-LC12" class="blob-code blob-code-inner js-file-line">      }</td>
</tr>
<tr>
<td id="file-boxingunboxing_sample-cs-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
<td id="file-boxingunboxing_sample-cs-LC13" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/105cc15fdf7cebd08bcfc7751793eca6/raw/5348461bc4a235d7e28b9a71b39c809506fbfab5/BoxingUnboxing_sample.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/105cc15fdf7cebd08bcfc7751793eca6#file-boxingunboxing_sample-cs" class="Link--inTextBlock"><br />
          BoxingUnboxing_sample.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>Let&#8217;s compile the application so we can find <em>BoxingUnboxingTest.exe</em> file in the output directory. Now we will use <a href="https://github.com/icsharpcode/ILSpy" target="_blank" rel="noopener">ILSpy</a> to see the IL code inside the executable.</p>
</p>
<p>As soon as the EXE file is opened in ILSpy, we can go directly to see <span style="color: #ff6600;">Main(string[]) : void</span> method&#8217;s compiled content, choosing &#8220;IL with C#&#8221; view to make it simpler for us:</p>
</p>
<figure id="attachment_2634" aria-describedby="caption-attachment-2634" style="width: 775px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/BoxingUnboxing_IL1.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2634" data-permalink="https://www.codejourney.net/net-internals-03-boxing-and-unboxing/boxingunboxing_il1/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/BoxingUnboxing_IL1.png?fit=775%2C687&amp;ssl=1" data-orig-size="775,687" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="BoxingUnboxing_IL1" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/BoxingUnboxing_IL1.png?fit=775%2C687&amp;ssl=1" class="wp-image-2634 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/BoxingUnboxing_IL1.png?resize=775%2C687&#038;ssl=1" alt="" width="775" height="687" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/BoxingUnboxing_IL1.png?w=775&amp;ssl=1 775w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/BoxingUnboxing_IL1.png?resize=300%2C266&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/BoxingUnboxing_IL1.png?resize=768%2C681&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/BoxingUnboxing_IL1.png?resize=720%2C638&amp;ssl=1 720w" sizes="auto, (max-width: 775px) 100vw, 775px" /></a><figcaption id="caption-attachment-2634" class="wp-caption-text">Boxing and Unboxing in IL</figcaption></figure>
<p>Notice the <span style="color: #ff6600;">box</span> statement just after the assignment of value type to reference type happens (<em>object obj = num</em>). Similarly for <span style="color: #ff6600;">unbox.any</span> statement just after assignment of reference type to value type (<em>int num2 = (int)obj</em>).</p>
</p>
<p>That&#8217;s how boxing and unboxing is represented in the IL.</p>
<h1>When do we box and unbox?</h1>
<p>The sample code above may seem naive and you may think &#8220;hey, but I never do such things&#8221;. That&#8217;s true in most cases, but values in our code are often boxed/unboxed even if we are not aware of that.</p>
<h2>Non-generic collections</h2>
<p>For instance, there still exists the old-school <span style="color: #ff6600;">ArrayList</span> collection:</p>
<figure id="attachment_2637" aria-describedby="caption-attachment-2637" style="width: 540px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ArrayList_Example.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2637" data-permalink="https://www.codejourney.net/net-internals-03-boxing-and-unboxing/arraylist_example/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ArrayList_Example.png?fit=540%2C139&amp;ssl=1" data-orig-size="540,139" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="ArrayList_Example" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ArrayList_Example.png?fit=540%2C139&amp;ssl=1" class="wp-image-2637 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ArrayList_Example.png?resize=540%2C139&#038;ssl=1" alt="" width="540" height="139" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ArrayList_Example.png?w=540&amp;ssl=1 540w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ArrayList_Example.png?resize=300%2C77&amp;ssl=1 300w" sizes="auto, (max-width: 540px) 100vw, 540px" /></a><figcaption id="caption-attachment-2637" class="wp-caption-text"><span style="font-size: 8pt;">ArrayList</span></figcaption></figure>
<p>which as you can see above has the <span style="color: #ff6600;">Add</span> method taking an <span style="color: #ff6600;">object</span> parameter. It means that when we&#8217;d like to add an integer to ArrayList:</p>
<style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91212433" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-boxingarraylist-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="BoxingArrayList.cs content, created by dsibinski on 05:02AM on August 08, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="BoxingArrayList.cs">
<tr>
<td id="file-boxingarraylist-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-boxingarraylist-cs-LC1" class="blob-code blob-code-inner js-file-line">  ArrayList al = new ArrayList();</td>
</tr>
<tr>
<td id="file-boxingarraylist-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-boxingarraylist-cs-LC2" class="blob-code blob-code-inner js-file-line">  int i = 8;</td>
</tr>
<tr>
<td id="file-boxingarraylist-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-boxingarraylist-cs-LC3" class="blob-code blob-code-inner js-file-line">  al.Add(i);</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/976151bb839c107a643e61dc5cab7632/raw/6d96d0a3f37aeb14c32105873e68a772ab1e2490/BoxingArrayList.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/976151bb839c107a643e61dc5cab7632#file-boxingarraylist-cs" class="Link--inTextBlock"><br />
          BoxingArrayList.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>boxing takes place:</p>
<figure id="attachment_2638" aria-describedby="caption-attachment-2638" style="width: 768px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ArrayList_BoxingIL.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2638" data-permalink="https://www.codejourney.net/net-internals-03-boxing-and-unboxing/arraylist_boxingil/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ArrayList_BoxingIL.png?fit=768%2C104&amp;ssl=1" data-orig-size="768,104" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="ArrayList_BoxingIL" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ArrayList_BoxingIL.png?fit=768%2C104&amp;ssl=1" class="wp-image-2638 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ArrayList_BoxingIL.png?resize=768%2C104&#038;ssl=1" alt="" width="768" height="104" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ArrayList_BoxingIL.png?w=768&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ArrayList_BoxingIL.png?resize=300%2C41&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ArrayList_BoxingIL.png?resize=720%2C98&amp;ssl=1 720w" sizes="auto, (max-width: 768px) 100vw, 768px" /></a><figcaption id="caption-attachment-2638" class="wp-caption-text"><span style="font-size: 8pt;">ArrayList.Add(int) &#8211; boxing (IL)</span></figcaption></figure>
<p>Such issues were eliminated by generics and <a href="https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic?view=netframework-4.7.2" target="_blank" rel="noopener">generic collections</a>.</p>
<h2>String concatenation</h2>
<p>Another interesting example is the concatenation of strings with value types using &#8220;+&#8221; operator:</p>
<style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91212451" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-boxing_stringconcat-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="Boxing_StringConcat.cs content, created by dsibinski on 05:05AM on August 08, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="Boxing_StringConcat.cs">
<tr>
<td id="file-boxing_stringconcat-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-boxing_stringconcat-cs-LC1" class="blob-code blob-code-inner js-file-line">  int i = 8;</td>
</tr>
<tr>
<td id="file-boxing_stringconcat-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-boxing_stringconcat-cs-LC2" class="blob-code blob-code-inner js-file-line">  string helloText = &quot;Hello&quot;;</td>
</tr>
<tr>
<td id="file-boxing_stringconcat-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-boxing_stringconcat-cs-LC3" class="blob-code blob-code-inner js-file-line">  string result = helloText + i;</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/0f647195dec951e469e6a7476620a4d4/raw/557c22a8c81d8dd985b545feb234a038ff6bd41d/Boxing_StringConcat.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/0f647195dec951e469e6a7476620a4d4#file-boxing_stringconcat-cs" class="Link--inTextBlock"><br />
          Boxing_StringConcat.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>Such operation involves <span style="color: #ff6600;">String.Concat</span> <a href="https://msdn.microsoft.com/en-us/library/kbseaaft(v=vs.110).aspx" target="_blank" rel="noopener">method&#8217;s version</a> taking two <span style="color: #ff6600;">object</span> parameters, so it implies boxing the integer first:</p>
<figure id="attachment_2639" aria-describedby="caption-attachment-2639" style="width: 626px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringConcatBoxingIL.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2639" data-permalink="https://www.codejourney.net/net-internals-03-boxing-and-unboxing/stringconcatboxingil/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringConcatBoxingIL.png?fit=626%2C265&amp;ssl=1" data-orig-size="626,265" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="StringConcatBoxingIL" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringConcatBoxingIL.png?fit=626%2C265&amp;ssl=1" class="wp-image-2639 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringConcatBoxingIL.png?resize=626%2C265&#038;ssl=1" alt="" width="626" height="265" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringConcatBoxingIL.png?w=626&amp;ssl=1 626w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringConcatBoxingIL.png?resize=300%2C127&amp;ssl=1 300w" sizes="auto, (max-width: 626px) 100vw, 626px" /></a><figcaption id="caption-attachment-2639" class="wp-caption-text"><span style="font-size: 8pt;">String and integer concatenation &#8211; boxing in IL</span></figcaption></figure>
<p>In order to avoid it, it&#8217;s enough to slightly modify the code by using <span style="color: #ff6600;">ToString()</span> method on the integer variable (for now ignoring ReSharper telling you it&#8217;s redundant ;)):</p>
<style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91212534" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-stringconcat_withtostring-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="StringConcat_withToString.cs content, created by dsibinski on 05:13AM on August 08, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="StringConcat_withToString.cs">
<tr>
<td id="file-stringconcat_withtostring-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-stringconcat_withtostring-cs-LC1" class="blob-code blob-code-inner js-file-line">  int i = 8;</td>
</tr>
<tr>
<td id="file-stringconcat_withtostring-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-stringconcat_withtostring-cs-LC2" class="blob-code blob-code-inner js-file-line">  string helloText = &quot;Hello&quot;;</td>
</tr>
<tr>
<td id="file-stringconcat_withtostring-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-stringconcat_withtostring-cs-LC3" class="blob-code blob-code-inner js-file-line">  string result = helloText + i.ToString();</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/91836b433c4ea1efa9d341f4a323e406/raw/fee89a0895b4aafa5a6a450fb84231dcef14bdb2/StringConcat_withToString.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/91836b433c4ea1efa9d341f4a323e406#file-stringconcat_withtostring-cs" class="Link--inTextBlock"><br />
          StringConcat_withToString.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>and there&#8217;s no boxing anymore, as now <span style="color: #ff6600;">String.Concat</span> <a href="https://msdn.microsoft.com/en-us/library/a6d350wd(v=vs.110).aspx" target="_blank" rel="noopener">method&#8217;s version</a> taking two <span style="color: #ff6600;">string</span> parameters is used:</p>
</p>
<figure id="attachment_2640" aria-describedby="caption-attachment-2640" style="width: 622px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringConcatNoBoxing.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2640" data-permalink="https://www.codejourney.net/net-internals-03-boxing-and-unboxing/stringconcatnoboxing/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringConcatNoBoxing.png?fit=622%2C273&amp;ssl=1" data-orig-size="622,273" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="StringConcatNoBoxing" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringConcatNoBoxing.png?fit=622%2C273&amp;ssl=1" class="wp-image-2640 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringConcatNoBoxing.png?resize=622%2C273&#038;ssl=1" alt="" width="622" height="273" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringConcatNoBoxing.png?w=622&amp;ssl=1 622w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/StringConcatNoBoxing.png?resize=300%2C132&amp;ssl=1 300w" sizes="auto, (max-width: 622px) 100vw, 622px" /></a><figcaption id="caption-attachment-2640" class="wp-caption-text"><span style="font-size: 8pt;">String concatenation with <em>ToString</em> usage &#8211; no boxing</span></figcaption></figure>
<p>There could be many more cases to present, but the goal is that you get a strong feeling what boxing and unboxing is and when it occurs.</p>
<h1>Performance implications of boxing and unboxing</h1>
<p>As we already know, boxing and unboxing imply some cost. In case of simple stuff like concatenating the string once with some integer, the performance gain by introducing <em>ToString</em> on integer first is unnoticeable. That&#8217;s why, as I wrote before, even ReSharper tells you to not do it:</p>
<figure id="attachment_2641" aria-describedby="caption-attachment-2641" style="width: 911px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ReSharper_DontUseToString.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2641" data-permalink="https://www.codejourney.net/net-internals-03-boxing-and-unboxing/resharper_dontusetostring/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ReSharper_DontUseToString.png?fit=911%2C126&amp;ssl=1" data-orig-size="911,126" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="ReSharper_DontUseToString" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ReSharper_DontUseToString.png?fit=911%2C126&amp;ssl=1" class="wp-image-2641 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ReSharper_DontUseToString.png?resize=911%2C126&#038;ssl=1" alt="" width="911" height="126" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ReSharper_DontUseToString.png?w=911&amp;ssl=1 911w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ReSharper_DontUseToString.png?resize=300%2C41&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ReSharper_DontUseToString.png?resize=768%2C106&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/08/ReSharper_DontUseToString.png?resize=720%2C100&amp;ssl=1 720w" sizes="auto, (max-width: 911px) 100vw, 911px" /></a><figcaption id="caption-attachment-2641" class="wp-caption-text"><span style="font-size: 8pt;">ReSharper &#8211; redundant ToString() call</span></figcaption></figure>
<p>In that case it&#8217;s better to keep the clarity of the code without <em>ToString</em> method.</p>
</p>
<p>The perspective changes when you need to perform such operations in a loop for hundreds or thousands times. In this case the execution of code using boxing can be even 150% longer than its equivalent with no boxing (you can create a simple application and measure the execution time of code with and without boxing or check <a href="https://www.codeproject.com/Articles/76153/Six-important-NET-concepts-Stack-heap-value-types" target="_blank" rel="noopener">this article</a>).</p>
</p>
<p>Boxed values also take more space in the memory than value types stored on the stack. Copying the value to/from the stack is also a cost. According to <a href="https://msdn.microsoft.com/en-us/library/ms173196.aspx" target="_blank" rel="noopener">MSDN</a>, boxing can generally take even 20 times longer that simple reference assignments, whereas unboxing can be 4 times slower than assignments.</p>
<h1>So&#8230; why to use boxing and unboxing?</h1>
<p>Despite all performance implications boxing and unboxing have, these concepts were introduced into .NET because of some reasons:</p>
<ul>
<li>there&#8217;s unified types system in .NET, which allows to &#8220;represent&#8221; both value and reference types in a similar way &#8211; thanks to boxing,</li>
<li>collections could be used for value types before generics were introduced into .NET,</li>
<li>it simplifies our code, like we saw for string concatenation and in most cases this clarity gives us much more than the performance we&#8217;d gain trying to avoid boxing.</li>
</ul>
<p>Boxing and unboxing are so common that we can&#8217;t avoid them. We should be aware how it works in order to be able to minimize their usage, but it should always be considered reasonably. Don&#8217;t spend time on optimizing your code, checking IL all the time to get to the point with the smallest possible number of <span style="color: #ff6600;">box</span> statements used. Keep in mind that the clarity of your code, its self-explanatory structure and comfort of reading is sometimes much more valuable than some small or barely noticeable performance gain.</p>
<h1>Summary</h1>
<p>In today&#8217;s post we saw what is boxing and unboxing, how it&#8217;s represented in the IL code and what implications on performance it may have. I hope it clarifies these commonly mentioned concepts for you, at least a bit <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
</p>
<p>If you&#8217;re interested in digging into nitty-gritty, low-level details of boxing and unboxing in .NET, I invit<span style="font-size: 1rem;">e you to read </span><a style="background-color: #ffffff; font-size: 1rem;" href="http://mattwarren.org/2017/08/02/A-look-at-the-internals-of-boxing-in-the-CLR/" target="_blank" rel="noopener">this great post by Matt Warren</a><span style="font-size: 1rem;"> about even more internal internals of boxing and unboxing <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></span></p>
</p>
<p>In the next posts <a href="https://www.codejourney.net/tag/dotnet-internals/" target="_blank" rel="noopener">in the series</a> we&#8217;re going to start exploring the garbage collection. If you have any suggestions or ideas for the coming articles, let me know in the comments (some of you already did on reddit &#8211; new posts scheduled <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> ).</p>
</p>
<p>See you (or better <em>read you</em> <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> ) next week!</p>
<p>The post <a href="https://www.codejourney.net/net-internals-03-boxing-and-unboxing/">[.NET Internals 03] Boxing and unboxing</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/net-internals-03-boxing-and-unboxing/feed/</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2622</post-id>	</item>
		<item>
		<title>[.NET Internals 02] Stack and heap &#8211;  .NET data structures</title>
		<link>https://www.codejourney.net/net-internals-02-stack-and-heap-net-data-structures/</link>
					<comments>https://www.codejourney.net/net-internals-02-stack-and-heap-net-data-structures/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Wed, 01 Aug 2018 06:00:09 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[dotnet-internals]]></category>
		<guid isPermaLink="false">http://www.dsibinski.pl/?p=2576</guid>

					<description><![CDATA[<p>In the second post of .NET Internals series, we&#8217;re going to investigate the organization of .NET process&#8217;s memory. We&#8217;ll see what is stack and heap and what kind of data is stored on each of these memory structures. If you&#8217;re here for the first time, I encourage you to first read the .NET Internals series&#8230;</p>
<p>The post <a href="https://www.codejourney.net/net-internals-02-stack-and-heap-net-data-structures/">[.NET Internals 02] Stack and heap &#8211;  .NET data structures</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In the second post of <a href="https://www.codejourney.net/tag/dotnet-internals/" target="_blank" rel="noopener">.NET Internals series</a>, we&#8217;re going to investigate the organization of .NET process&#8217;s memory. We&#8217;ll see what is <em>stack</em> and <em>heap</em> and what kind of data is stored on each of these memory structures.<br />
<span id="more-2576"></span></p>
<p>If you&#8217;re here for the first time, I encourage you to first read the .NET Internals series <a href="https://www.codejourney.net/2018/07/net-internals-01-basics-of-memory-structure/" target="_blank" rel="noopener">introductory post explaining the basics of memory structure</a>.</p>
<h1>Memory division</h1>
<p>By default, when the .NET application is started and virtual address space is allocated for the process (as we saw in the <a href="https://www.codejourney.net/2018/07/net-internals-01-basics-of-memory-structure/" target="_blank" rel="noopener">previous post</a>), the following data structures, represented as <strong>heaps</strong>, are created:</p>
<ul>
<li>Code Heap &#8211; storing <a href="https://www.telerik.com/blogs/understanding-net-just-in-time-compilation" target="_blank" rel="noopener" data-wplink-edit="true">JIT-compiled</a> native code,</li>
<li>Small Object Heap (SOH) &#8211; storing objects of size less than 85 kilobytes,</li>
<li>Large Object Heap (LOH) &#8211; storing objects of size greater than 85 kilobytes*,</li>
<li>Process Heap.</li>
</ul>
<p><span style="font-size: 10pt;">*side note: there&#8217;s an exception for arrays of <span style="font-family: terminal, monaco, monospace;">double</span>,  which are allocated on the LOH much before reaching 85K (<span style="font-family: terminal, monaco, monospace;">double[]</span> is considered &#8220;large&#8221; when it exceeds 1000 elements). This is for the sake of 32-bit code optimization. More details <a href="https://stackoverflow.com/questions/8951836/why-large-object-heap-and-why-do-we-care" target="_blank" rel="noopener">here</a> and <a href="https://stackoverflow.com/questions/11791038/large-object-heap-fragmentation-issues-with-arrays" target="_blank" rel="noopener">here</a>.</span></p>
</p>
<p>Division of storing small and large objects on different heaps has its performance reasons, which will be covered in the next posts about garbage collection.</p>
</p>
<p>Elements placed on the heap have their <em>addresses</em>, which are a kind of pointers to the place in memory where the particular object is located.</p>
</p>
<p>Heap is however not the only data structure used by .NET process. There&#8217;s also a <strong>stack</strong>, which helps in tracking code&#8217;s execution and storing some special types of data. We&#8217;ll now see in details how stack and heap are used and organized.</p>
<h1>Stack</h1>
<figure id="attachment_2581" aria-describedby="caption-attachment-2581" style="width: 391px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Stack_Wikipedia.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2581" data-permalink="https://www.codejourney.net/net-internals-02-stack-and-heap-net-data-structures/stack_wikipedia/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Stack_Wikipedia.png?fit=391%2C281&amp;ssl=1" data-orig-size="391,281" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Stack_Wikipedia" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Stack_Wikipedia.png?fit=391%2C281&amp;ssl=1" class="wp-image-2581 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Stack_Wikipedia.png?resize=391%2C281&#038;ssl=1" alt="" width="391" height="281" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Stack_Wikipedia.png?w=391&amp;ssl=1 391w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Stack_Wikipedia.png?resize=300%2C216&amp;ssl=1 300w" sizes="auto, (max-width: 391px) 100vw, 391px" /></a><figcaption id="caption-attachment-2581" class="wp-caption-text"><span style="font-size: 8pt;">Stack Data Structure, source: Wikipedia</span></figcaption></figure>
<p>Stack is a memory structure organized as LIFO (last-in-first-out) collection. If you think about it, it&#8217;s perfect for storing anything that may soon need to be used (easily popped out from the top of the stack). This nature of stack leads to its two main purposes: <strong>keeping track of execution order</strong> and<strong> storing value types variables</strong>.</p>
<h2>Keeping track of execution order &#8211; call stack</h2>
<p>Most of the code we write is wrapped into classes and methods, which can call another methods, which call another methods etc. .NET Framework must all the time keep track of this execution&#8217;s order. Moreover, it also has to remember the state of variables and parameters of the method calling another method, while this another method executes (to be able to restore the calling method&#8217;s state after the called method returns).</p>
</p>
<p>As soon as any method is called, .NET initializes a <em>stack frame</em> (kind of container) which stores all data necessary to execute the method: parameters, local variables and address of the line of code to go back to when the method finishes.  Stack frames are created on the stack on top of each other. Each method has its own stack frame. All that behavior is well illustrated on the figure below.</p>
<figure id="attachment_2586" aria-describedby="caption-attachment-2586" style="width: 684px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Stack_Frames_Wikipedia.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2586" data-permalink="https://www.codejourney.net/net-internals-02-stack-and-heap-net-data-structures/stack_frames_wikipedia/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Stack_Frames_Wikipedia.png?fit=684%2C558&amp;ssl=1" data-orig-size="684,558" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Stack_Frames_Wikipedia" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Stack_Frames_Wikipedia.png?fit=684%2C558&amp;ssl=1" class="wp-image-2586 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Stack_Frames_Wikipedia.png?resize=684%2C558&#038;ssl=1" alt="" width="684" height="558" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Stack_Frames_Wikipedia.png?w=684&amp;ssl=1 684w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Stack_Frames_Wikipedia.png?resize=300%2C245&amp;ssl=1 300w" sizes="auto, (max-width: 684px) 100vw, 684px" /></a><figcaption id="caption-attachment-2586" class="wp-caption-text">Call stack frames, source: Wikipedia</figcaption></figure>
<h3></h3>
<p>Stack used for storing the execution order is often referred to as <strong>call stack, execution stack </strong>or <strong>program stack</strong>.</p>
</p>
<p>Take a look at the following code:</p>
<style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91069473" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-stack_methodsexecutionexample1-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="Stack_MethodsExecutionExample1.cs content, created by dsibinski on 08:34PM on July 31, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="Stack_MethodsExecutionExample1.cs">
<tr>
<td id="file-stack_methodsexecutionexample1-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-stack_methodsexecutionexample1-cs-LC1" class="blob-code blob-code-inner js-file-line">  void Method1()</td>
</tr>
<tr>
<td id="file-stack_methodsexecutionexample1-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-stack_methodsexecutionexample1-cs-LC2" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-stack_methodsexecutionexample1-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-stack_methodsexecutionexample1-cs-LC3" class="blob-code blob-code-inner js-file-line">      Method2(12);</td>
</tr>
<tr>
<td id="file-stack_methodsexecutionexample1-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-stack_methodsexecutionexample1-cs-LC4" class="blob-code blob-code-inner js-file-line">      Console.WriteLine(&quot;Goodbye&quot;);</td>
</tr>
<tr>
<td id="file-stack_methodsexecutionexample1-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-stack_methodsexecutionexample1-cs-LC5" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
<tr>
<td id="file-stack_methodsexecutionexample1-cs-L6" class="blob-num js-line-number js-blob-rnum" data-line-number="6"></td>
<td id="file-stack_methodsexecutionexample1-cs-LC6" class="blob-code blob-code-inner js-file-line">  void Method2(int testData)</td>
</tr>
<tr>
<td id="file-stack_methodsexecutionexample1-cs-L7" class="blob-num js-line-number js-blob-rnum" data-line-number="7"></td>
<td id="file-stack_methodsexecutionexample1-cs-LC7" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-stack_methodsexecutionexample1-cs-L8" class="blob-num js-line-number js-blob-rnum" data-line-number="8"></td>
<td id="file-stack_methodsexecutionexample1-cs-LC8" class="blob-code blob-code-inner js-file-line">      int multiplier = 2;</td>
</tr>
<tr>
<td id="file-stack_methodsexecutionexample1-cs-L9" class="blob-num js-line-number js-blob-rnum" data-line-number="9"></td>
<td id="file-stack_methodsexecutionexample1-cs-LC9" class="blob-code blob-code-inner js-file-line">      Console.WriteLine(&quot;Value is &quot; + testData);</td>
</tr>
<tr>
<td id="file-stack_methodsexecutionexample1-cs-L10" class="blob-num js-line-number js-blob-rnum" data-line-number="10"></td>
<td id="file-stack_methodsexecutionexample1-cs-LC10" class="blob-code blob-code-inner js-file-line">      Method3(testData* multiplier);</td>
</tr>
<tr>
<td id="file-stack_methodsexecutionexample1-cs-L11" class="blob-num js-line-number js-blob-rnum" data-line-number="11"></td>
<td id="file-stack_methodsexecutionexample1-cs-LC11" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
<tr>
<td id="file-stack_methodsexecutionexample1-cs-L12" class="blob-num js-line-number js-blob-rnum" data-line-number="12"></td>
<td id="file-stack_methodsexecutionexample1-cs-LC12" class="blob-code blob-code-inner js-file-line">  void Method3(int data)</td>
</tr>
<tr>
<td id="file-stack_methodsexecutionexample1-cs-L13" class="blob-num js-line-number js-blob-rnum" data-line-number="13"></td>
<td id="file-stack_methodsexecutionexample1-cs-LC13" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-stack_methodsexecutionexample1-cs-L14" class="blob-num js-line-number js-blob-rnum" data-line-number="14"></td>
<td id="file-stack_methodsexecutionexample1-cs-LC14" class="blob-code blob-code-inner js-file-line">      Console.WriteLine(&quot;Double &quot; + data);</td>
</tr>
<tr>
<td id="file-stack_methodsexecutionexample1-cs-L15" class="blob-num js-line-number js-blob-rnum" data-line-number="15"></td>
<td id="file-stack_methodsexecutionexample1-cs-LC15" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
<tr>
<td id="file-stack_methodsexecutionexample1-cs-L16" class="blob-num js-line-number js-blob-rnum" data-line-number="16"></td>
<td id="file-stack_methodsexecutionexample1-cs-LC16" class="blob-code blob-code-inner js-file-line">// source: C. Farrell and N. Harrison &#8211; Under the Hood of .NET Memory Management</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/d21ce0c0fe4fb65cec0739fa18980944/raw/e58ac87fc596034e2263edcfa0586bfeebf6752c/Stack_MethodsExecutionExample1.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/d21ce0c0fe4fb65cec0739fa18980944#file-stack_methodsexecutionexample1-cs" class="Link--inTextBlock"><br />
          Stack_MethodsExecutionExample1.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>In order to call <span style="font-family: terminal, monaco, monospace;">Method2</span>, the framework must save an execution return address which will be the next line of code to execute after <span style="font-family: terminal, monaco, monospace;">Method2</span> finishes (line 4 in the example above). This address altogether with parameters and local variables of the calling and called methods are stored on the call stack, as the schema below presents.</p>
</p>
<figure id="attachment_2588" aria-describedby="caption-attachment-2588" style="width: 421px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ExecutionStack1.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2588" data-permalink="https://www.codejourney.net/net-internals-02-stack-and-heap-net-data-structures/executionstack1/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ExecutionStack1.png?fit=421%2C274&amp;ssl=1" data-orig-size="421,274" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="ExecutionStack1" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ExecutionStack1.png?fit=421%2C274&amp;ssl=1" class="wp-image-2588 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ExecutionStack1.png?resize=421%2C274&#038;ssl=1" alt="" width="421" height="274" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ExecutionStack1.png?w=421&amp;ssl=1 421w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ExecutionStack1.png?resize=300%2C195&amp;ssl=1 300w" sizes="auto, (max-width: 421px) 100vw, 421px" /></a><figcaption id="caption-attachment-2588" class="wp-caption-text"><span style="font-size: 8pt;">Call stack for methods 1-3, source: C. Farrell and N. Harrison &#8211; <em>Under the Hood of .NET Memory Management</em></span></figcaption></figure>
<p>You can also notice what happens when <span style="font-family: terminal, monaco, monospace;">Method3</span> returns (its stack frame is popped out from the stack &#8211; it disappears).</p>
<h2>Storing value types</h2>
<p>Stack is also used to store variables of any of .NET value types, including <span style="font-family: terminal, monaco, monospace;">bool</span>, <span style="font-family: terminal, monaco, monospace;">decimal</span>, <span style="font-family: terminal, monaco, monospace;">int</span> etc. Full list of .NET value types can be found <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/value-types-table" target="_blank" rel="noopener">here</a>.</p>
</p>
<p>Value types are basically the types which keep the data and memory in the same location. What&#8217;s also interesting to know is that all value-typed local variables of the method allocated on the stack are cleaned-up after the method&#8217;s execution finishes. It happens because the method&#8217;s stack frame becomes unreachable &#8211; stack has some pointer to the beginning of the top-level stack frame (<em>current</em> stack frame pointer), which is simply moved to the second stack frame from the top as soon as the method&#8217;s execution is finished (the data is still physically there, but it&#8217;s not reachable by default .NET mechanisms).</p>
<h1>Heap</h1>
<p>Heap is similar to stack, but if the stack can be imagined as a series of boxes stacked on top of each other, where we always push or pop the top one, heap contains boxes that can be accessed at any time. The boxes in the heap are placed in different places, not necessarily on the top of each other. To access one of the boxes we don&#8217;t need to pop out the top ones first.</p>
<h2>Storing reference types</h2>
<p>All other variables, which are not value types i.e. are either <span style="font-family: terminal, monaco, monospace;">string</span> or <span style="font-family: terminal, monaco, monospace;">object</span> (or deriving from one of these, so all classes, interfaces and delegates) are referred to as <strong>reference types</strong>. All reference types are allocated on the managed heap (SOH or LOH, depending on their size). However, even though an object is allocated on the heap, a <em>reference</em> to it (address on the heap) is stored on the stack.</p>
</p>
<p>Consider the following code:</p>
<style>.gist table { margin-bottom: 0; }</style>
<div style="tab-size: 8" id="gist91069943" class="gist">
<div class="gist-file" translate="no" data-color-mode="light" data-light-theme="light">
<div class="gist-data">
<div class="js-gist-file-update-container js-task-list-container">
<div id="file-heap_example-cs" class="file my-2">
<div itemprop="text"
      class="Box-body p-0 blob-wrapper data type-c  "
      style="overflow: auto" tabindex="0" role="region"
      aria-label="Heap_example.cs content, created by dsibinski on 09:03PM on July 31, 2018."
    ></p>
<div class="js-check-hidden-unicode js-blob-code-container blob-code-content">
<p>  <template class="js-file-alert-template"></p>
<div data-view-component="true" class="flash flash-warn flash-full d-flex flex-items-center">
  <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
    <span><br />
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.<br />
      <a class="Link--inTextBlock" href="https://github.co/hiddenchars" target="_blank">Learn more about bidirectional Unicode characters</a><br />
    </span></p>
<div data-view-component="true" class="flash-action">        <a href="{{ revealButtonHref }}" data-view-component="true" class="btn-sm btn">    Show hidden characters<br />
</a>
</div>
</div>
<p></template><br />
<template class="js-line-alert-template"><br />
  <span aria-label="This line has hidden Unicode characters" data-view-component="true" class="line-alert tooltipped tooltipped-e"><br />
    <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">
    <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
</svg><br />
</span></template></p>
<table data-hpc class="highlight tab-size js-file-line-container" data-tab-size="4" data-paste-markdown-skip data-tagsearch-path="Heap_example.cs">
<tr>
<td id="file-heap_example-cs-L1" class="blob-num js-line-number js-blob-rnum" data-line-number="1"></td>
<td id="file-heap_example-cs-LC1" class="blob-code blob-code-inner js-file-line">  void Method1()</td>
</tr>
<tr>
<td id="file-heap_example-cs-L2" class="blob-num js-line-number js-blob-rnum" data-line-number="2"></td>
<td id="file-heap_example-cs-LC2" class="blob-code blob-code-inner js-file-line">  {</td>
</tr>
<tr>
<td id="file-heap_example-cs-L3" class="blob-num js-line-number js-blob-rnum" data-line-number="3"></td>
<td id="file-heap_example-cs-LC3" class="blob-code blob-code-inner js-file-line">      MyClass myObj = new MyClass();</td>
</tr>
<tr>
<td id="file-heap_example-cs-L4" class="blob-num js-line-number js-blob-rnum" data-line-number="4"></td>
<td id="file-heap_example-cs-LC4" class="blob-code blob-code-inner js-file-line">      Console.WriteLine(myObj.ToString());</td>
</tr>
<tr>
<td id="file-heap_example-cs-L5" class="blob-num js-line-number js-blob-rnum" data-line-number="5"></td>
<td id="file-heap_example-cs-LC5" class="blob-code blob-code-inner js-file-line">  }</td>
</tr>
</table>
</div></div>
</p></div>
</div></div>
<div class="gist-meta">
        <a href="https://gist.github.com/dsibinski/68ad6011969b6f0105ce680d42b0aab5/raw/374167390f346a64c2649ef2a0b60632d56a1585/Heap_example.cs" style="float:right" class="Link--inTextBlock">view raw</a><br />
        <a href="https://gist.github.com/dsibinski/68ad6011969b6f0105ce680d42b0aab5#file-heap_example-cs" class="Link--inTextBlock"><br />
          Heap_example.cs<br />
        </a><br />
        hosted with &#10084; by <a class="Link--inTextBlock" href="https://github.com">GitHub</a>
      </div>
</p></div>
</div>
<p>The figure below presents how stack and heap would look like here in terms of allocated data:</p>
<figure id="attachment_2590" aria-describedby="caption-attachment-2590" style="width: 1011px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Heap.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2590" data-permalink="https://www.codejourney.net/net-internals-02-stack-and-heap-net-data-structures/heap/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Heap.png?fit=1011%2C498&amp;ssl=1" data-orig-size="1011,498" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Heap" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Heap.png?fit=1011%2C498&amp;ssl=1" class="wp-image-2590 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Heap.png?resize=1011%2C498&#038;ssl=1" alt="" width="1011" height="498" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Heap.png?w=1011&amp;ssl=1 1011w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Heap.png?resize=300%2C148&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Heap.png?resize=768%2C378&amp;ssl=1 768w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/Heap.png?resize=720%2C355&amp;ssl=1 720w" sizes="auto, (max-width: 1011px) 100vw, 1011px" /></a><figcaption id="caption-attachment-2590" class="wp-caption-text"><span style="font-size: 8pt;">Stack and Heap with reference variable, source: C. Farrell and N. Harrison &#8211; <em>Under the Hood of .NET Memory Management</em></span></figcaption></figure>
<p>The &#8220;OBJREF&#8221; stored on the stack is actually a pointer (reference) to the <span style="font-family: terminal, monaco, monospace;">MyClass</span> object on the heap.</p>
</p>
<p>NOTE:  <span style="font-family: terminal, monaco, monospace; color: #ff6600;">MyClass myObj</span> statement doesn&#8217;t allocate any space on the heap for <span style="font-family: terminal, monaco, monospace;">myObj</span> variable. It only creates &#8220;OBJREF&#8221; variable on the stack, initializing it with <span style="color: #ff6600;">NULL</span> value. By the time <span style="color: #ff6600;">new</span> statement is used, the actual memory allocation on the heap takes place and the reference&#8217;s value is set.</p>
<h1>Value types vs reference types (stack vs heap)</h1>
<p>The crucial difference between value and reference types is that when a <strong>value type</strong> variable is passed to another method as parameter or just assigned to another value type variable, its value is <strong>copied into the new variable</strong>. That&#8217;s why when passing a value type to another method, which modifies this variable (parameter), when the method returns the original variable&#8217;s value is not changed (it was its copy which was used inside the called method). Figure below shows this behavior.</p>
<figure id="attachment_2593" aria-describedby="caption-attachment-2593" style="width: 616px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ValueTypesCopy.jpg?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2593" data-permalink="https://www.codejourney.net/net-internals-02-stack-and-heap-net-data-structures/valuetypescopy/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ValueTypesCopy.jpg?fit=616%2C276&amp;ssl=1" data-orig-size="616,276" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="ValueTypesCopy" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ValueTypesCopy.jpg?fit=616%2C276&amp;ssl=1" class="wp-image-2593 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ValueTypesCopy.jpg?resize=616%2C276&#038;ssl=1" alt="" width="616" height="276" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ValueTypesCopy.jpg?w=616&amp;ssl=1 616w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ValueTypesCopy.jpg?resize=300%2C134&amp;ssl=1 300w" sizes="auto, (max-width: 616px) 100vw, 616px" /></a><figcaption id="caption-attachment-2593" class="wp-caption-text"><span style="font-size: 8pt;">Value types copying, source: <a href="https://www.codeproject.com/Articles/76153/Six-important-NET-concepts-Stack-heap-value-types" target="_blank" rel="noopener">link</a></span></figcaption></figure>
<p>It&#8217;s different in case of reference types. When reference type variable is assigned to another <strong>reference type</strong> variable (or method&#8217;s parameter), <strong>it&#8217;s not its value which is copied, but only the</strong> <strong>reference</strong> to it (address in the memory where the data is actually stored on the heap). In effect, the new variable (or method&#8217;s parameter) still points to the same place in memory, so modifying such reference type variable inside the called method will also be in effect outside of the method. This case is illustrated below.</p>
<figure id="attachment_2594" aria-describedby="caption-attachment-2594" style="width: 616px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ReferencesCopying.jpg?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2594" data-permalink="https://www.codejourney.net/net-internals-02-stack-and-heap-net-data-structures/referencescopying/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ReferencesCopying.jpg?fit=616%2C331&amp;ssl=1" data-orig-size="616,331" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="ReferencesCopying" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ReferencesCopying.jpg?fit=616%2C331&amp;ssl=1" class="wp-image-2594 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ReferencesCopying.jpg?resize=616%2C331&#038;ssl=1" alt="" width="616" height="331" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ReferencesCopying.jpg?w=616&amp;ssl=1 616w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ReferencesCopying.jpg?resize=300%2C161&amp;ssl=1 300w" sizes="auto, (max-width: 616px) 100vw, 616px" /></a><figcaption id="caption-attachment-2594" class="wp-caption-text"><span style="font-size: 8pt;">References passing, source: <a href="https://www.codeproject.com/Articles/76153/Six-important-NET-concepts-Stack-heap-value-types" target="_blank" rel="noopener">link</a></span></figcaption></figure>
<p>Of course, storing some data on the stack and some on the heap (moreover: different types of heaps) has its precise purpose, which we&#8217;re going to explore in the coming posts <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h1>Summary</h1>
<p>In today&#8217;s post we went through stack and heap, two data structures used for storing value and reference types and tracking execution order of .NET application. In the next posts <a href="https://www.codejourney.net/tag/dotnet-internals/" target="_blank" rel="noopener">in the series</a> we will see what is <em>boxing</em> and <em>unboxing</em> and how it can affect application&#8217;s performance. We will also examine the <em>garbage collection</em> process in details.</p>
</p>
<p>Stay tuned!</p>
<script>(function() {
	window.mc4wp = window.mc4wp || {
		listeners: [],
		forms: {
			on: function(evt, cb) {
				window.mc4wp.listeners.push(
					{
						event   : evt,
						callback: cb
					}
				);
			}
		}
	}
})();
</script><!-- Mailchimp for WordPress v4.12.2 - https://wordpress.org/plugins/mailchimp-for-wp/ --><form id="mc4wp-form-5" class="mc4wp-form mc4wp-form-2612" method="post" data-id="2612" data-name="Download a free guide form" ><div class="mc4wp-form-fields"><table bgcolor="#f2f6f5"><tr><td> <p><p>
    <label>
<h1 style="">
  <center>GET A FREE GUIDE <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f381.png" alt="🎁" class="wp-smiley" style="height: 1em; max-height: 1em;" /></center>
      </h1>        
      <h2 style="font-family: Helvetica">
        <center>16 STEPS TO BECOME <br/>.NET FULL STACK WEB DEVELOPER </br>IN 2025</center>
      </h2>
</p>
  <center><div>
	<input type="email" name="EMAIL" placeholder="Email address" required />
    <p>
    <input type="text" name="FNAME" placeholder="Your name"
    required="">
  </p>
  </div>
    <center>

	<center><input type="submit" value="DOWNLOAD THE FREE GUIDE" style="color: #7b1fa2; font-weight:bold; font-size: 20px" /></center>
<p style="font-size: 12px; font-style: italic;">After you sign up, I may be sending you some emails with additional free content from time to time.
<br/>No spam, only awesome stuff</p>
</p></td></tr></table>

</div><label style="display: none !important;">Leave this field empty if you're human: <input type="text" name="_mc4wp_honeypot" value="" tabindex="-1" autocomplete="off" /></label><input type="hidden" name="_mc4wp_timestamp" value="1778077255" /><input type="hidden" name="_mc4wp_form_id" value="2612" /><input type="hidden" name="_mc4wp_form_element_id" value="mc4wp-form-5" /><div class="mc4wp-response"></div></form><!-- / Mailchimp for WordPress Plugin --></p>
<p>The post <a href="https://www.codejourney.net/net-internals-02-stack-and-heap-net-data-structures/">[.NET Internals 02] Stack and heap &#8211;  .NET data structures</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/net-internals-02-stack-and-heap-net-data-structures/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2576</post-id>	</item>
		<item>
		<title>[.NET Internals 01] Basics of memory structure</title>
		<link>https://www.codejourney.net/net-internals-01-basics-of-memory-structure/</link>
					<comments>https://www.codejourney.net/net-internals-01-basics-of-memory-structure/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Wed, 25 Jul 2018 06:00:52 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[dotnet-internals]]></category>
		<guid isPermaLink="false">http://www.dsibinski.pl/?p=2523</guid>

					<description><![CDATA[<p>Have you ever wondered about what&#8217;s under the hood of the applications you develop? Ever been surprised that there&#8217;s no need to worry about memory allocation and deallocation using high-level programming languages such as Java or C# after leaving the university* ? Still remember (old) C++ times with delete statement? By this post, I&#8217;d like to&#8230;</p>
<p>The post <a href="https://www.codejourney.net/net-internals-01-basics-of-memory-structure/">[.NET Internals 01] Basics of memory structure</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Have you ever wondered about what&#8217;s under the hood of the applications you develop?</p>
<p>Ever been surprised that there&#8217;s no need to worry about memory allocation and deallocation using high-level programming languages such as Java or C# after leaving the university<strong>* </strong>?</p>
</p>
<p>Still remember (old) C++ times with <span style="color: #ff6600;">delete</span> statement?</p>
<h1></h1>
<figure id="attachment_2524" aria-describedby="caption-attachment-2524" style="width: 300px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/CPP_Pointers_Meme.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2524" data-permalink="https://www.codejourney.net/net-internals-01-basics-of-memory-structure/cpp_pointers_meme/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/CPP_Pointers_Meme.png?fit=470%2C414&amp;ssl=1" data-orig-size="470,414" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="CPP_Pointers_Meme" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/CPP_Pointers_Meme.png?fit=470%2C414&amp;ssl=1" class="wp-image-2524 size-medium" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/CPP_Pointers_Meme.png?resize=300%2C264&#038;ssl=1" alt="" width="300" height="264" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/CPP_Pointers_Meme.png?resize=300%2C264&amp;ssl=1 300w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/CPP_Pointers_Meme.png?w=470&amp;ssl=1 470w" sizes="auto, (max-width: 300px) 100vw, 300px" /></a><figcaption id="caption-attachment-2524" class="wp-caption-text"><span style="font-size: 8pt;">Source: &#8220;Arnaud Porterie &#8211; The Truth About C++&#8221;</span></figcaption></figure>
<p>By this post, I&#8217;d like to introduce a new &#8220;.NET Internals&#8221; series on the blog. I will be publishing a <strong>new post on .NET internal concepts every Wednesday. </strong>No end date for the moment <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /><br />
<span id="more-2523"></span></p>
<p>Posts within the series will be mostly about memory management and performance aspects of .NET applications. All discussed concepts are applicable to most of the modern programming platforms, but the examples will be based on .NET Framework.</p>
</p>
<p>If you&#8217;re interested in such topics, I encourage you to check this blog every Wednesday starting today <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
</p>
<p><span style="font-size: 8pt;"><strong>*</strong>there is <strong>1 assumption</strong> and <strong>1 fact</strong> here:</span></p>
<ul>
<li><span style="font-size: 8pt;"><strong>assumption</strong>: you used to program in C/C++ (before C++11) on the university,</span></li>
<li><span style="font-size: 8pt;"><strong>fact</strong>: that&#8217;s not true you don&#8217;t need to worry about memory management using high-level programming languages; wait for the next posts to get to know why.</span></li>
</ul>
<h1></h1>
<h1>CLR</h1>
<p>Each application targeting .NET is managed by CLR (<em>Common Language Runtime</em>), which is a part of .NET Framework, which must be installed on the computer on which the .NET application is launched &#8211; the exception are <a href="https://docs.microsoft.com/en-us/dotnet/core/deploying/#self-contained-deployments-scd" target="_blank" rel="noopener">.NET Core self-contained apps</a>, which we are not discussing in this series. By default, the CLR is loaded by each .NET process as a hosted process (so the CLR runs as a part of .NET application).</p>
</p>
<p>This CLR &#8220;layer&#8221; is responsible for various things while our application is running:</p>
<ul>
<li>executing CIL (<em>Common Intermediate Language</em>),</li>
<li>ensuring type safety,</li>
<li>handling exceptions,</li>
<li>managing threads,</li>
<li>garbage collection.</li>
</ul>
<h1>Memory structure</h1>
<p>Already running application is represented as a <em>process</em> in the operating system. As software developers we know that such process saves some data into the memory, which is determined by the amount of RAM available on the computer. However, process never operates on this &#8220;open memory&#8221; &#8211; only OS has direct access to it. When the CLR is launched within .NET process, it requests some amount of RAM from the operating system. This memory chunk is called <strong><em>virtual address space</em></strong>. Each process has its own virtual address space, but <strong>all processes running on the same machine share the same physical memory</strong>.</p>
<h2>32-bit OS</h2>
<p>Do you remember 32-bit editions of Windows XP, which could only use 4GBs of RAM (with <a href="https://superuser.com/questions/27086/why-does-windows-only-show-about-3-5-gb-of-my-4-gb-of-ram" target="_blank" rel="noopener">even less visible to the user</a>)? The reason for that is that <strong>in 32-bit operating systems total virtual address space is 4GBs</strong>, usually divided into two equal chunks &#8211; first one owned by the OS and the second one prepared for user processes. The diagram below presents.</p>
<figure id="attachment_2542" aria-describedby="caption-attachment-2542" style="width: 268px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/System_process_VAS_32.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2542" data-permalink="https://www.codejourney.net/net-internals-01-basics-of-memory-structure/system_process_vas_32/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/System_process_VAS_32.png?fit=268%2C267&amp;ssl=1" data-orig-size="268,267" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="System_process_VAS_32" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/System_process_VAS_32.png?fit=268%2C267&amp;ssl=1" class="wp-image-2542 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/System_process_VAS_32.png?resize=268%2C267&#038;ssl=1" alt="" width="268" height="267" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/System_process_VAS_32.png?w=268&amp;ssl=1 268w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/System_process_VAS_32.png?resize=150%2C150&amp;ssl=1 150w" sizes="auto, (max-width: 268px) 100vw, 268px" /></a><figcaption id="caption-attachment-2542" class="wp-caption-text"><span style="font-size: 8pt;">Source: <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/gettingstarted/virtual-address-spaces" target="_blank" rel="noopener">https://docs.microsoft.com/en-us/windows-hardware/drivers/gettingstarted/virtual-address-spaces</a></span></figcaption></figure>
<h2>64-bit OS</h2>
<p>In 64-bit Windows theoretical amount of virtual address space is 16 exabytes (2<sup>64</sup> bytes). In reality, only a part of it is used: 8-terabyte chunk is used for user space and portions of 248-terabyte are used for the OS:</p>
<figure id="attachment_2544" aria-describedby="caption-attachment-2544" style="width: 227px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/System_process_VAS_64.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2544" data-permalink="https://www.codejourney.net/net-internals-01-basics-of-memory-structure/system_process_vas_64/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/System_process_VAS_64.png?fit=227%2C329&amp;ssl=1" data-orig-size="227,329" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="System_process_VAS_64" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/System_process_VAS_64.png?fit=227%2C329&amp;ssl=1" class="wp-image-2544 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/System_process_VAS_64.png?resize=227%2C329&#038;ssl=1" alt="" width="227" height="329" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/System_process_VAS_64.png?w=227&amp;ssl=1 227w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/System_process_VAS_64.png?resize=207%2C300&amp;ssl=1 207w" sizes="auto, (max-width: 227px) 100vw, 227px" /></a><figcaption id="caption-attachment-2544" class="wp-caption-text"><span style="font-size: 8pt;">Source: <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/gettingstarted/virtual-address-spaces" target="_blank" rel="noopener">https://docs.microsoft.com/en-us/windows-hardware/drivers/gettingstarted/virtual-address-spaces</a></span></figcaption></figure>
<h2>Sharing memory between processes</h2>
<p>What seems to be critical to understand is how this whole <strong>virtual memory is shared between processes</strong>. As we said before, multiple processes share the same memory, but accessing different (separate) chunks of it. Let us illustrate once more:</p>
<figure id="attachment_2545" aria-describedby="caption-attachment-2545" style="width: 399px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ProcessesSharingMemory.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2545" data-permalink="https://www.codejourney.net/net-internals-01-basics-of-memory-structure/processessharingmemory/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ProcessesSharingMemory.png?fit=399%2C364&amp;ssl=1" data-orig-size="399,364" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="ProcessesSharingMemory" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ProcessesSharingMemory.png?fit=399%2C364&amp;ssl=1" class="wp-image-2545 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ProcessesSharingMemory.png?resize=399%2C364&#038;ssl=1" alt="" width="399" height="364" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ProcessesSharingMemory.png?w=399&amp;ssl=1 399w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/ProcessesSharingMemory.png?resize=300%2C274&amp;ssl=1 300w" sizes="auto, (max-width: 399px) 100vw, 399px" /></a><figcaption id="caption-attachment-2545" class="wp-caption-text"><span style="font-size: 8pt;">Source: <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/gettingstarted/virtual-address-spaces" target="_blank" rel="noopener">https://docs.microsoft.com/en-us/windows-hardware/drivers/gettingstarted/virtual-address-spaces</a></span></figcaption></figure>
<p>As can be seen, <strong>each process reserves different <em>pages</em> of memory when it&#8217;s needed</strong>. Even though the default 2GBs of virtual memory reserved for a single process may seem to be a lot, every developer needs to be aware that <strong>when an <em>allocation </em>(reservation of memory chunk) is made</strong> (manually or by memory management system) the <strong>virtual memory manager needs to find a single, continuous virtual memory block</strong> large enough to store the requested amount of data. This rule leads to the presence of &#8220;holes&#8221; in the memory. This virtual memory <em>fragmentation</em> is well-presented on the diagram below:</p>
<figure id="attachment_2546" aria-describedby="caption-attachment-2546" style="width: 138px" class="wp-caption aligncenter"><a href="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/VirtualMemoryFragmentation.png?ssl=1" target="_blank" rel="noopener"><img data-recalc-dims="1" loading="lazy" decoding="async" data-attachment-id="2546" data-permalink="https://www.codejourney.net/net-internals-01-basics-of-memory-structure/virtualmemoryfragmentation/" data-orig-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/VirtualMemoryFragmentation.png?fit=138%2C305&amp;ssl=1" data-orig-size="138,305" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="VirtualMemoryFragmentation" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/VirtualMemoryFragmentation.png?fit=138%2C305&amp;ssl=1" class="wp-image-2546 size-full" src="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/VirtualMemoryFragmentation.png?resize=138%2C305&#038;ssl=1" alt="" width="138" height="305" srcset="https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/VirtualMemoryFragmentation.png?w=138&amp;ssl=1 138w, https://i0.wp.com/www.codejourney.net/wp-content/uploads/2018/07/VirtualMemoryFragmentation.png?resize=136%2C300&amp;ssl=1 136w" sizes="auto, (max-width: 138px) 100vw, 138px" /></a><figcaption id="caption-attachment-2546" class="wp-caption-text"><span style="font-size: 8pt;">Virtual memory fragmentation</span></figcaption></figure>
<p>However, this requirement of finding a continuous block to be allocated refers only to the virtual memory. Physical memory is divided into pages, which can be stored in totally different places &#8211; as you can see on the diagram above with Notepad.exe application using continuous blocks of its virtual memory, but <a href="https://docs.microsoft.com/en-us/windows/desktop/memory/reserving-and-committing-memory" target="_blank" rel="noopener"><em>committed</em></a> to noncontiguous pages scattered in various physical locations.</p>
</p>
<p>If the process requests for too much memory, which cannot be continuously allocated in the virtual address space (your process is out of virtual memory) or no more virtual memory can be committed (assigned) to the physical storage, it can result in <span style="color: #ff6600;">OutOfMemoryException</span> thrown by .NET code.</p>
<h1>Summary</h1>
<p>This was the introductory post of my new <a href="https://www.codejourney.net/tag/dotnet-internals/" target="_blank" rel="noopener">.NET Internals series</a>. We saw what are the basic concepts of the memory structure, learnt what is virtual address space, how physical memory is shared between processes and why Windows XP was able to handle only 4GBs of RAM <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
</p>
<p>See you next Wednesday!</p>
</p>
<script>(function() {
	window.mc4wp = window.mc4wp || {
		listeners: [],
		forms: {
			on: function(evt, cb) {
				window.mc4wp.listeners.push(
					{
						event   : evt,
						callback: cb
					}
				);
			}
		}
	}
})();
</script><!-- Mailchimp for WordPress v4.12.2 - https://wordpress.org/plugins/mailchimp-for-wp/ --><form id="mc4wp-form-6" class="mc4wp-form mc4wp-form-2612" method="post" data-id="2612" data-name="Download a free guide form" ><div class="mc4wp-form-fields"><table bgcolor="#f2f6f5"><tr><td> <p><p>
    <label>
<h1 style="">
  <center>GET A FREE GUIDE <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f381.png" alt="🎁" class="wp-smiley" style="height: 1em; max-height: 1em;" /></center>
      </h1>        
      <h2 style="font-family: Helvetica">
        <center>16 STEPS TO BECOME <br/>.NET FULL STACK WEB DEVELOPER </br>IN 2025</center>
      </h2>
</p>
  <center><div>
	<input type="email" name="EMAIL" placeholder="Email address" required />
    <p>
    <input type="text" name="FNAME" placeholder="Your name"
    required="">
  </p>
  </div>
    <center>

	<center><input type="submit" value="DOWNLOAD THE FREE GUIDE" style="color: #7b1fa2; font-weight:bold; font-size: 20px" /></center>
<p style="font-size: 12px; font-style: italic;">After you sign up, I may be sending you some emails with additional free content from time to time.
<br/>No spam, only awesome stuff</p>
</p></td></tr></table>

</div><label style="display: none !important;">Leave this field empty if you're human: <input type="text" name="_mc4wp_honeypot" value="" tabindex="-1" autocomplete="off" /></label><input type="hidden" name="_mc4wp_timestamp" value="1778077255" /><input type="hidden" name="_mc4wp_form_id" value="2612" /><input type="hidden" name="_mc4wp_form_element_id" value="mc4wp-form-6" /><div class="mc4wp-response"></div></form><!-- / Mailchimp for WordPress Plugin -->
<p>The post <a href="https://www.codejourney.net/net-internals-01-basics-of-memory-structure/">[.NET Internals 01] Basics of memory structure</a> appeared first on <a href="https://www.codejourney.net">CodeJourney.net</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codejourney.net/net-internals-01-basics-of-memory-structure/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2523</post-id>	</item>
	</channel>
</rss>
