{"id":213,"date":"2022-03-12T14:25:18","date_gmt":"2022-03-12T14:25:18","guid":{"rendered":"https:\/\/baldsolutions.com\/?p=213"},"modified":"2022-03-12T14:37:12","modified_gmt":"2022-03-12T14:37:12","slug":"for-vs-foreach-performance-difference","status":"publish","type":"post","link":"https:\/\/baldsolutions.com\/index.php\/2022\/03\/12\/for-vs-foreach-performance-difference\/","title":{"rendered":"For vs Foreach &#8211; performance difference"},"content":{"rendered":"\n<h1 class=\"wp-block-heading\">Introduction<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">Iterating through collections is part and parcel of programming. As a C# developer you&#8217;ve probably used <code>for<\/code> and <code>foreach<\/code>.  Both helps to iterate through a collection, but it&#8217;s worth to be aware that there are ins and outs. In this post I will show and explain performance differences between iterating through an array and a list using <code>for<\/code> and <code>foreach<\/code>.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Performance<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s consider the following code snippet:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class CollectionsHolder\r\n{\r\n    private readonly List&lt;int> _list;\r\n    private readonly int&#91;] _array;\r\n\r\n    public CollectionsHolder(int count)\r\n    {\r\n        _list = new List&lt;int>(Enumerable.Range(0, count));\r\n        _array = new int&#91;count];\r\n    }\r\n\r\n    public void ForLoopList()\r\n    {\r\n        for (int i = 0; i &lt; _list.Count; i++) { }\r\n    }\r\n\r\n    public void ForeachLoopList()\r\n    {\r\n        foreach (var item in _list) { }\r\n    }\r\n\r\n    public void ForLoopArray()\r\n    {\r\n        for (int i = 0; i &lt; _array.Length; i++) { }\r\n    }\r\n\r\n    public void ForeachLoopArray()\r\n    {\r\n        foreach (var item in _array) { }\r\n    }\r\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>CollectionsHolder<\/code> class stores two collections: <code>_list <\/code>and <code>_array<\/code>. There are four methods that do nothing but iterate through a particular collection &#8211; pretty useless but good enough in terms of benchmarking.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Benchmark (1_000_000_000 elements per collection) results for these four methods stand as follows:<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"423\" height=\"160\" src=\"https:\/\/baldsolutions.com\/wp-content\/uploads\/2022\/03\/image.png\" alt=\"\" class=\"wp-image-216\" srcset=\"https:\/\/baldsolutions.com\/wp-content\/uploads\/2022\/03\/image.png 423w, https:\/\/baldsolutions.com\/wp-content\/uploads\/2022\/03\/image-300x113.png 300w\" sizes=\"auto, (max-width: 423px) 100vw, 423px\" \/><\/figure><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">It turns out that <code>foreach<\/code> iteration time is ~7 times slower than using classic <code>for<\/code> when it comes to the list iteration. Surprisingly, <code>foreach<\/code> iteration through the array lasts the same as using <code>for<\/code> loop.  The question is, why <code>ForLoopList<\/code>, <code>ForLoopArray <\/code>and <code>ForeachLoopArray<\/code> last the same, meanwhile <code>ForeachLoopList<\/code> lasts much longer?<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Explanation<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">To get immediate insight I strongly recommend to visit the <a href=\"https:\/\/sharplab.io\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"sharplab.io\">sharplab.io<\/a> website. Long story short, the sharplab.io can be used e.g. to see the C# (without syntactic sugar), IL or ASM translation of the C# code (F#, Visual Basic and IL as well at the time of writing the post).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Once you&#8217;re there just paste the aforementioned code snippet and focus on the right side:<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"949\" height=\"910\" src=\"https:\/\/baldsolutions.com\/wp-content\/uploads\/2022\/03\/image-4.png\" alt=\"\" class=\"wp-image-232\" srcset=\"https:\/\/baldsolutions.com\/wp-content\/uploads\/2022\/03\/image-4.png 949w, https:\/\/baldsolutions.com\/wp-content\/uploads\/2022\/03\/image-4-300x288.png 300w, https:\/\/baldsolutions.com\/wp-content\/uploads\/2022\/03\/image-4-768x736.png 768w\" sizes=\"auto, (max-width: 949px) 100vw, 949px\" \/><\/figure><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">As you can see the code from the left side has been translated into the code on the right side (no syntactic sugar). The mystery seems to be solved! The <code>ForLoopList<\/code>, <code>ForLoopArray <\/code>and <code>ForeachLoopArray<\/code> methods have been translated into straightforward <code>while<\/code> loop, hence the execution time of the methods are almost the same (~330ms in our benchmark).  However, the <code>ForeachLoopList<\/code> looks slightly more complicated. These additional lines of code, i.e. getting enumerator ( <code>_list.GetEnumerator()<\/code>), using <code>enumerator.MoveNext()<\/code> and so on, cause additional overhead in terms of the method execution time. <\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Summary<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">In conclusion, <code>for<\/code> and <code>foreach<\/code>, despite the similar usage, might perform differently in terms of time execution. Having that in mind you might think, that you should use <code>for<\/code> any time, but don&#8217;t be fooled. There is something called &#8220;premature optimization&#8221; &#8211; it is a tendency to spend to much time to optimize unnecessary things. Don&#8217;t get me wrong, optimization is crucial, but you should always take into consideration if it is reasonable. Moreover, using <code>foreach<\/code> has its pros, e.g. using it against a list is (in my opinion) much more readable. Readability is sometimes undervalued. Poorly written code is hard to understand, therefore its maintenance is more expensive. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">As always I&#8217;ve prepared an example and you can find it on my <a href=\"https:\/\/github.com\/tglowka\/baldsolutions\/tree\/master\/.NET\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"github\">github<\/a>, project: <a href=\"https:\/\/github.com\/tglowka\/baldsolutions\/tree\/master\/.NET\/for-vs-foreach\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a><a href=\"https:\/\/github.com\/tglowka\/baldsolutions\/tree\/master\/.NET\/for-vs-foreach\">for-vs-foreach<\/a>, benchmark project: <a href=\"https:\/\/github.com\/tglowka\/baldsolutions\/tree\/master\/.NET\/for-vs-foreach-benchmark\" target=\"_blank\" rel=\"noreferrer noopener\"><a href=\"https:\/\/github.com\/tglowka\/baldsolutions\/tree\/master\/.NET\/for-vs-foreach-benchmark\">for-vs-foreach-benchmark<\/a><\/a>. I encourage you to go through the code, debug it and try to test your own scenarios.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Have a nice day, bye!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Introduction Iterating through collections is part and parcel of programming. As a C# developer you&#8217;ve probably used for and foreach. Both helps to iterate through&#8230;<\/p>\n<div class=\"more-link-wrapper\"><a class=\"more-link\" href=\"https:\/\/baldsolutions.com\/index.php\/2022\/03\/12\/for-vs-foreach-performance-difference\/\">Continue reading<span class=\"screen-reader-text\">For vs Foreach &#8211; performance difference<\/span><\/a><\/div>\n","protected":false},"author":3,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[2],"tags":[],"class_list":["post-213","post","type-post","status-publish","format-standard","hentry","category-net","entry"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/posts\/213","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/comments?post=213"}],"version-history":[{"count":26,"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/posts\/213\/revisions"}],"predecessor-version":[{"id":244,"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/posts\/213\/revisions\/244"}],"wp:attachment":[{"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/media?parent=213"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/categories?post=213"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/tags?post=213"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}