Smart Coding, Think Outside of Loop

Sometimes, careless looping may be an overhead on processor.

 

OK, let’s take a quick look at the below code. In this code, we are looping from 1 to 200 and each time we are creating a two new LinkButton variables and do something with them.

                       

For J = 1 To 200

    Dim button1 As New LinkButton

    Dim button2 As New LinkButton

    button1 = e.Item.Controls(J)

    button2 = e.Item.Controls(J)

Next

 

The same code I could rewrite as following. In this code, I define variables outside the loop and they are initialized once only and later their value is changing.

 

Dim button1 As New LinkButton

Dim button2 As New LinkButton   

For J = 1 To 200

   button1 = e.Item.Controls(J)

   button2 = e.Item.Controls(J)

Next

 

You may not notice any performance difference but in best practices world, the second code snippet is preferable. What if variable you are initializing inside the loop are too large? It may even lead to serious performance issues.

 

What is the difference? Let’s think it in this way. I have to eat 200 donuts at once and every time, I take a new donut, I use a new plate. Alternatively, I could reuse the first plate. In second case, I save 199 plates ;-). Isn’t second choice the wise one?

 

OK here is one more classic example, I see a lot.

 

Here is one if loop:

 

     if (i <= 2)

     {

                // Dome something here

 

                // Display Message

                textBox1.Text = "Loop done";

            }

            else

            {

                // Dome something ELSE here

 

                // Display Message

                textBox1.Text = "Loop done";

            } 

 

Since textBox1.Text is same no matter if IF condition is true or false. So, we can take it outside of loop like this:

 

            if (i <= 2)

            {

                // Dome something here

            }

            else

            {

                // Dome something ELSE here           

            }

            // Display Message

            textBox1.Text = "Loop done";

           

Ebook Download
View all
Learn
View all