Recommended c# Syntax Code for High Performance RRS feed

  • Question

  • Hello,

    There are some syntax that you should not use for instance "foreach" is takes a lot of resources compare to "for (in i=0; i < 10; i++)"

    Another approach is to use array index instead of using "List<T>"

    Do you know anythong more about similiar of syntax code that is not usage to use and also syntax code is recommended to use?

    Thank you!
    Thursday, January 23, 2020 1:04 PM

All replies

  • A for is going to be faster than a foreach, see the following. Also consider when performing a task what is the impact between the two, many times with small iterations and nothing else going on either is fine vs say you are working with a large amount of information and a good deal of assertions.

    This also goes back to your first question on profiling.

    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

    Thursday, January 23, 2020 1:13 PM
  • What kind of an application are you thinking about?

    I mean for most of the things I have seen for performance are not selecting between for and foreach, but implementing correctly what is done in the loop. So I would not make it a general rule for performance that never use foreach, but for instead. Leaving foreach out means that you can not use Linq or basically anything else that rely on IEnumerable/IEnumerator interfaces and most of the cases those are too big advantages over performance between for and foreach.

    Thursday, January 23, 2020 2:54 PM
  • Performance is not the only criteria by which to judge code.  "foreach" is easier to write and less error prone than the equivalent for(;;) loop.  That's a significant benefit.  Unless you KNOW that your for loop is consuming significant CPU time, it is an utter waste of programmer resources to worry about optimizing it.

    First, make it work.  Then, make it correct.  Then, make it fast.  Premature optimization is the world's curse.

    Tim Roberts | Driver MVP Emeritus | Providenza &amp; Boekelheide, Inc.

    Friday, January 24, 2020 8:09 AM
  • Optimize your time, not CPU time.  Long, long ago it was more important to worry about each millisecond, but as computation speed increased dramatically it became more important to be an efficient programmer.

    Convert between VB, C#, C++, & Java (
    Instant C# - VB to C# Converter
    Instant VB - C# to VB Converter

    Friday, January 24, 2020 2:53 PM