Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Basic C# question
Message
From
05/07/2006 14:39:45
 
 
To
05/07/2006 13:42:17
General information
Forum:
ASP.NET
Category:
Other
Environment versions
Environment:
C# 2.0
Miscellaneous
Thread ID:
01133939
Message ID:
01133948
Views:
13
>This is a basic question to enhance my understanding.
>
>In a loop is the condition tokenized once and checked every time or is it calculated in every iteration?
>
>Take this example:
>
>for (int i = 0; i < this.TreeView1.Nodes.Count; i++)
>{
>}
>
>
>or is it more efficient (faster) to do:
>
>int nCount = this.TreeView1.Nodes.Count;
>for (int i = 0; i < nCount; i++)
>{
>}
>
>
>Granted, in a short loop it does not really matter as the time differences would be measured in microseconds but the principle of the thing is what I'm looking for.
>
>Every little bit of new knowledge on .NET helps :)

Hmm, good question. I'm not sure that fundamentally there is any difference in your two snippets. Since it's possible that the code in the loop could change either this.TreeView1.Nodes.Count or nCount, then the question really boils down to whether the value is re-evaluated for each loop, or if it's fixed at the start of the first loop. I don't know the answer to that off the top of my head.

It's probably infinitesimally quicker to use nCount instead of this.TreeView1.Nodes.Count, assuming there are enough loops to offset the overhead of declaring and initializing the extra variable. There could be a large speed gain if TreeView1 is an ActiveX; my understanding is that COM calls like that are expensive and that your second snippet is best practice in these cases.

UPDATE: Docs for the C# FOR command:

"The for loop executes a statement or a block of statements repeatedly until a specified expression evaluates to false."

Seems to me, this means the logical expression is evaluated before each loop, not just once.
Regards. Al

"Violence is the last refuge of the incompetent." -- Isaac Asimov
"Never let your sense of morals prevent you from doing what is right." -- Isaac Asimov

Neither a despot, nor a doormat, be

Every app wants to be a database app when it grows up
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform