C# -- Why for each slower than For loop RRS feed


  • Here is a short an easy to understand explanation.

    A foreach loop requires the use of an Enumerator to iterate over the collection, which requires accessing the Current property and calling the MoveNext method on each iteration, which take some processing time.

    The for loop only has to call get_Item (an indexer) on each iteration, so that’s one less call than the foreach loop, which makes a slight difference in performance.

    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    profile for Karen Payne on Stack Exchange

    • Marked as answer by Sudip_inn Friday, March 27, 2020 2:09 PM
    Friday, March 27, 2020 9:40 AM