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.

Join the conversation! Your thoughts help the community grow.