Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Declaring variables inside loops - inefficient?

Declaring variables inside loops - inefficient?

Scheduled Pinned Locked Moved C#
tutorialquestioncode-review
15 Posts 7 Posters 1 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • A Offline
    A Offline
    Adam Brown 3
    wrote on last edited by
    #1

    Is there any efficiency lost in declaring variables inside loops, or is the compiler smart enough to optimize the code so the variable is really only reserved once? For example, would it be more efficient to move the variable declaratrions outrside of the loops? Example 1

    for (int i = 0; i < tblApplications.Controls.Count; i++) { ... }

    Is it more efficient to write it like this:

    int i;
    for (i = 0; i < tblApplications.Controls.Count; i++) { ... }

    Example 2

    foreach (GridViewRow row in grdUsers.Rows)
    {
    string value= row.Cells[1].Text;
    }

    Is it more efficient to write it like this:

    GridViewRow row;
    string value;
    foreach (row in grdUsers.Rows)
    {
    value= row.Cells[1].Text;
    }

    R L E L K 5 Replies Last reply
    0
    • A Adam Brown 3

      Is there any efficiency lost in declaring variables inside loops, or is the compiler smart enough to optimize the code so the variable is really only reserved once? For example, would it be more efficient to move the variable declaratrions outrside of the loops? Example 1

      for (int i = 0; i < tblApplications.Controls.Count; i++) { ... }

      Is it more efficient to write it like this:

      int i;
      for (i = 0; i < tblApplications.Controls.Count; i++) { ... }

      Example 2

      foreach (GridViewRow row in grdUsers.Rows)
      {
      string value= row.Cells[1].Text;
      }

      Is it more efficient to write it like this:

      GridViewRow row;
      string value;
      foreach (row in grdUsers.Rows)
      {
      value= row.Cells[1].Text;
      }

      R Offline
      R Offline
      riced
      wrote on last edited by
      #2

      I think you'll find it makes no difference as far as efficiency is concerned - it's not going to declare the variables each time around the loop. However, there is a difference. In your first example i goes out of scope when the loop finishes. In the alternative, i is still in scope when the loop finishes (with a value equal to the Count).

      Regards David R --------------------------------------------------------------- "Every program eventually becomes rococo, and then rubble." - Alan Perlis The only valid measurement of code quality: WTFs/minute.

      1 Reply Last reply
      0
      • A Adam Brown 3

        Is there any efficiency lost in declaring variables inside loops, or is the compiler smart enough to optimize the code so the variable is really only reserved once? For example, would it be more efficient to move the variable declaratrions outrside of the loops? Example 1

        for (int i = 0; i < tblApplications.Controls.Count; i++) { ... }

        Is it more efficient to write it like this:

        int i;
        for (i = 0; i < tblApplications.Controls.Count; i++) { ... }

        Example 2

        foreach (GridViewRow row in grdUsers.Rows)
        {
        string value= row.Cells[1].Text;
        }

        Is it more efficient to write it like this:

        GridViewRow row;
        string value;
        foreach (row in grdUsers.Rows)
        {
        value= row.Cells[1].Text;
        }

        L Offline
        L Offline
        Lost User
        wrote on last edited by
        #3

        There is no difference at the MSIL level. In both cases, the variable would get a named local variable slot.

        1 Reply Last reply
        0
        • A Adam Brown 3

          Is there any efficiency lost in declaring variables inside loops, or is the compiler smart enough to optimize the code so the variable is really only reserved once? For example, would it be more efficient to move the variable declaratrions outrside of the loops? Example 1

          for (int i = 0; i < tblApplications.Controls.Count; i++) { ... }

          Is it more efficient to write it like this:

          int i;
          for (i = 0; i < tblApplications.Controls.Count; i++) { ... }

          Example 2

          foreach (GridViewRow row in grdUsers.Rows)
          {
          string value= row.Cells[1].Text;
          }

          Is it more efficient to write it like this:

          GridViewRow row;
          string value;
          foreach (row in grdUsers.Rows)
          {
          value= row.Cells[1].Text;
          }

          E Offline
          E Offline
          Ennis Ray Lynch Jr
          wrote on last edited by
          #4

          Check your apps memory usage. Each declaration using more memory in .NET, even though it shouldn't One interesting note, however:

          foreach(string abc in someList){
          }//end look
          string abc = "test";

          Is a compiler error.

          Need custom software developed? I do custom programming based primarily on MS tools with an emphasis on C# development and consulting. I also do Android Programming as I find it a refreshing break from the MS. "And they, since they Were not the one dead, turned to their affairs" -- Robert Frost

          1 Reply Last reply
          0
          • A Adam Brown 3

            Is there any efficiency lost in declaring variables inside loops, or is the compiler smart enough to optimize the code so the variable is really only reserved once? For example, would it be more efficient to move the variable declaratrions outrside of the loops? Example 1

            for (int i = 0; i < tblApplications.Controls.Count; i++) { ... }

            Is it more efficient to write it like this:

            int i;
            for (i = 0; i < tblApplications.Controls.Count; i++) { ... }

            Example 2

            foreach (GridViewRow row in grdUsers.Rows)
            {
            string value= row.Cells[1].Text;
            }

            Is it more efficient to write it like this:

            GridViewRow row;
            string value;
            foreach (row in grdUsers.Rows)
            {
            value= row.Cells[1].Text;
            }

            L Offline
            L Offline
            Luc Pattyn
            wrote on last edited by
            #5

            it is all the same. However

            for (int i = 0; i < tblApplications.Controls.Count; i++) { ... }

            is counting those Controls over and over, you may gain some by storing that in a local variable once. :)

            Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

            Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.

            1 Reply Last reply
            0
            • A Adam Brown 3

              Is there any efficiency lost in declaring variables inside loops, or is the compiler smart enough to optimize the code so the variable is really only reserved once? For example, would it be more efficient to move the variable declaratrions outrside of the loops? Example 1

              for (int i = 0; i < tblApplications.Controls.Count; i++) { ... }

              Is it more efficient to write it like this:

              int i;
              for (i = 0; i < tblApplications.Controls.Count; i++) { ... }

              Example 2

              foreach (GridViewRow row in grdUsers.Rows)
              {
              string value= row.Cells[1].Text;
              }

              Is it more efficient to write it like this:

              GridViewRow row;
              string value;
              foreach (row in grdUsers.Rows)
              {
              value= row.Cells[1].Text;
              }

              K Offline
              K Offline
              Keith Barrow
              wrote on last edited by
              #6

              The first form (declaring the variable with the loop) is more efficient in terms of memory, the scope of the variable stays within the loop, so when the loop ends, the variable is ready for garbage collection. Declaring the variable before the loop increases its scope to the calling method (you might want this in some cases, but neither of the cases you described as like that), when the loop ends, the variable remains in scope until the calling method fishes. Declaring the variable before the loop is also less readable, it also makes the code harder (or at least uglier) to refactor if, for example, you want to take the loop out into its own method. Finally, and this is my opinion, I don't think you should worry too much about efficiency unless your method is used a lot. The things you need to do to make code efficient quite often makes it less readable (and harder to maintain). There was some quote like "prior optimisation is the thief of good code". Most code doesn't put that much stress on a server (unless you are looping/using it constantly, or the application has an inherently heavy workload, e.g.batch processing), and you should only really optimise code in such circumstances (and then really really optimise the most often executed code. That said, you also need to make sure your code doesn't become bloated, so it's always a bit of a balancing act. Hope this answers your question. [Edit] I'm waiting to be flamed now....

              ragnaroknrol The Internet is For Porn[^]
              Pete o'Hanlon: If it wasn't insulting tools, I'd say you were dumber than a bag of spanners.

              A L 2 Replies Last reply
              0
              • K Keith Barrow

                The first form (declaring the variable with the loop) is more efficient in terms of memory, the scope of the variable stays within the loop, so when the loop ends, the variable is ready for garbage collection. Declaring the variable before the loop increases its scope to the calling method (you might want this in some cases, but neither of the cases you described as like that), when the loop ends, the variable remains in scope until the calling method fishes. Declaring the variable before the loop is also less readable, it also makes the code harder (or at least uglier) to refactor if, for example, you want to take the loop out into its own method. Finally, and this is my opinion, I don't think you should worry too much about efficiency unless your method is used a lot. The things you need to do to make code efficient quite often makes it less readable (and harder to maintain). There was some quote like "prior optimisation is the thief of good code". Most code doesn't put that much stress on a server (unless you are looping/using it constantly, or the application has an inherently heavy workload, e.g.batch processing), and you should only really optimise code in such circumstances (and then really really optimise the most often executed code. That said, you also need to make sure your code doesn't become bloated, so it's always a bit of a balancing act. Hope this answers your question. [Edit] I'm waiting to be flamed now....

                ragnaroknrol The Internet is For Porn[^]
                Pete o'Hanlon: If it wasn't insulting tools, I'd say you were dumber than a bag of spanners.

                A Offline
                A Offline
                Adam Brown 3
                wrote on last edited by
                #7

                This is exactly the type of answer I was looking for - thanks! Adam

                1 Reply Last reply
                0
                • K Keith Barrow

                  The first form (declaring the variable with the loop) is more efficient in terms of memory, the scope of the variable stays within the loop, so when the loop ends, the variable is ready for garbage collection. Declaring the variable before the loop increases its scope to the calling method (you might want this in some cases, but neither of the cases you described as like that), when the loop ends, the variable remains in scope until the calling method fishes. Declaring the variable before the loop is also less readable, it also makes the code harder (or at least uglier) to refactor if, for example, you want to take the loop out into its own method. Finally, and this is my opinion, I don't think you should worry too much about efficiency unless your method is used a lot. The things you need to do to make code efficient quite often makes it less readable (and harder to maintain). There was some quote like "prior optimisation is the thief of good code". Most code doesn't put that much stress on a server (unless you are looping/using it constantly, or the application has an inherently heavy workload, e.g.batch processing), and you should only really optimise code in such circumstances (and then really really optimise the most often executed code. That said, you also need to make sure your code doesn't become bloated, so it's always a bit of a balancing act. Hope this answers your question. [Edit] I'm waiting to be flamed now....

                  ragnaroknrol The Internet is For Porn[^]
                  Pete o'Hanlon: If it wasn't insulting tools, I'd say you were dumber than a bag of spanners.

                  L Offline
                  L Offline
                  Lost User
                  wrote on last edited by
                  #8

                  But it's an int in the first case, no GC in sight

                  K 1 Reply Last reply
                  0
                  • L Lost User

                    But it's an int in the first case, no GC in sight

                    K Offline
                    K Offline
                    Keith Barrow
                    wrote on last edited by
                    #9

                    Correct, but it will still be popped out of the stack when it goes out of scope. The second example definitely does get destroyed by the GC. My main points were that the increasing the scope out of the loop, both decreases the readability, and takes an (an albeit small) amount of memory while [edit- removed Geordie English] it remains in scope.

                    ragnaroknrol The Internet is For Porn[^]
                    Pete o'Hanlon: If it wasn't insulting tools, I'd say you were dumber than a bag of spanners.

                    modified on Monday, July 19, 2010 12:16 PM

                    L 1 Reply Last reply
                    0
                    • K Keith Barrow

                      Correct, but it will still be popped out of the stack when it goes out of scope. The second example definitely does get destroyed by the GC. My main points were that the increasing the scope out of the loop, both decreases the readability, and takes an (an albeit small) amount of memory while [edit- removed Geordie English] it remains in scope.

                      ragnaroknrol The Internet is For Porn[^]
                      Pete o'Hanlon: If it wasn't insulting tools, I'd say you were dumber than a bag of spanners.

                      modified on Monday, July 19, 2010 12:16 PM

                      L Offline
                      L Offline
                      Lost User
                      wrote on last edited by
                      #10

                      Keith Barrow wrote:

                      Correct, but it will still be popped out of the stack when it goes out of scope.

                      No it won't, it will get an entry in the .locals section and its value will stay valid even though it would be "out of scope" according to C# - and the JIT compiler is an idiot and will permanently (as long as the stack frame is active) allocate stack space for it at least while a debugger is attached (not sure how to get the optimized code)

                      K 1 Reply Last reply
                      0
                      • L Lost User

                        Keith Barrow wrote:

                        Correct, but it will still be popped out of the stack when it goes out of scope.

                        No it won't, it will get an entry in the .locals section and its value will stay valid even though it would be "out of scope" according to C# - and the JIT compiler is an idiot and will permanently (as long as the stack frame is active) allocate stack space for it at least while a debugger is attached (not sure how to get the optimized code)

                        K Offline
                        K Offline
                        Keith Barrow
                        wrote on last edited by
                        #11

                        Wow, that is carp (by which I mean a little brown fish or sorts :-)) design. Still, you learn something new everyday I suppose. Are there any article around about how this stuff works (I mean the relationship between the call stack an the variables that get declared and how these unwind, rather than GC)? I have just realised that I have no clue what happens under the hood, and I hate not knowing stuff ( and sadly there is a lot of stuff I don't know....).

                        ragnaroknrol The Internet is For Porn[^]
                        Pete o'Hanlon: If it wasn't insulting tools, I'd say you were dumber than a bag of spanners.

                        L L 2 Replies Last reply
                        0
                        • K Keith Barrow

                          Wow, that is carp (by which I mean a little brown fish or sorts :-)) design. Still, you learn something new everyday I suppose. Are there any article around about how this stuff works (I mean the relationship between the call stack an the variables that get declared and how these unwind, rather than GC)? I have just realised that I have no clue what happens under the hood, and I hate not knowing stuff ( and sadly there is a lot of stuff I don't know....).

                          ragnaroknrol The Internet is For Porn[^]
                          Pete o'Hanlon: If it wasn't insulting tools, I'd say you were dumber than a bag of spanners.

                          L Offline
                          L Offline
                          Lost User
                          wrote on last edited by
                          #12

                          I don't know about articles.. I just took a look at the disassembly window in the debugger, and at the MSIL view in the Reflector Local variables are "destroyed" (that is, they will be at a lower address than ESP) in the function epilogue, temporary variables (from expression evaluation) in MSIL live on the operand stack and in the Actual* Code they are in registers (unless there are too many, then they get some stack space as well) * But all that is still based on the "JIT without optimizations" since I can't figure out how to get the real, optimized, code. I've tried doing a kernel32@DebugBreak but then it refuses to debug any managed code and gets stuck in some native stack frames..

                          1 Reply Last reply
                          0
                          • K Keith Barrow

                            Wow, that is carp (by which I mean a little brown fish or sorts :-)) design. Still, you learn something new everyday I suppose. Are there any article around about how this stuff works (I mean the relationship between the call stack an the variables that get declared and how these unwind, rather than GC)? I have just realised that I have no clue what happens under the hood, and I hate not knowing stuff ( and sadly there is a lot of stuff I don't know....).

                            ragnaroknrol The Internet is For Porn[^]
                            Pete o'Hanlon: If it wasn't insulting tools, I'd say you were dumber than a bag of spanners.

                            L Offline
                            L Offline
                            Luc Pattyn
                            wrote on last edited by
                            #13

                            Keith Barrow wrote:

                            there is a lot of stuff I don't know...

                            There is but one consoling thought: the more you study, the more you realize the things you don't know are growing in number even more rapidly. :)

                            Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

                            Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.

                            P 1 Reply Last reply
                            0
                            • L Luc Pattyn

                              Keith Barrow wrote:

                              there is a lot of stuff I don't know...

                              There is but one consoling thought: the more you study, the more you realize the things you don't know are growing in number even more rapidly. :)

                              Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

                              Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.

                              P Offline
                              P Offline
                              Pete OHanlon
                              wrote on last edited by
                              #14

                              This is true. I studied so much that I realised I was learning less and less about more and more, so now I know nothing about anything.

                              "WPF has many lovers. It's a veritable porn star!" - Josh Smith

                              As Braveheart once said, "You can take our freedom but you'll never take our Hobnobs!" - Martin Hughes.

                              My blog | My articles | MoXAML PowerToys | Onyx

                              L 1 Reply Last reply
                              0
                              • P Pete OHanlon

                                This is true. I studied so much that I realised I was learning less and less about more and more, so now I know nothing about anything.

                                "WPF has many lovers. It's a veritable porn star!" - Josh Smith

                                As Braveheart once said, "You can take our freedom but you'll never take our Hobnobs!" - Martin Hughes.

                                My blog | My articles | MoXAML PowerToys | Onyx

                                L Offline
                                L Offline
                                Luc Pattyn
                                wrote on last edited by
                                #15

                                Pete O'Hanlon wrote:

                                so now I know nothing about anything.

                                However you succeed rather well at hiding that. :laugh:

                                Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

                                Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.

                                1 Reply Last reply
                                0
                                Reply
                                • Reply as topic
                                Log in to reply
                                • Oldest to Newest
                                • Newest to Oldest
                                • Most Votes


                                • Login

                                • Don't have an account? Register

                                • Login or register to search.
                                • First post
                                  Last post
                                0
                                • Categories
                                • Recent
                                • Tags
                                • Popular
                                • World
                                • Users
                                • Groups