Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop variable declaration for the condition in .NET Source code

Tags:

c#

.net

I've been digging through ExpressionVisitor in .NET and I found this for loop,

for (int i = 0, n = nodes.Count; i < n; i++) 
{
    Expression node = Visit(nodes[i]);
    if (newNodes != null) 
    {
        newNodes[i] = node;
    } 
    else if (!object.ReferenceEquals(node, nodes[i])) 
    {
        newNodes = new Expression[n];
        for (int j = 0; j < i; j++) 
        {
            newNodes[j] = nodes[j];
        }
        newNodes[i] = node;
    }
}

Now is there any particular reason why is that: i = 0, n = nodes.Count; i < n?

Is there any performance gain from this that is not in i = 0; i < nodes.Count?

like image 927
Radoslav.Ivanov Avatar asked Dec 01 '16 04:12

Radoslav.Ivanov


People also ask

Can you put a condition in a for loop?

You can put a for loop inside an if statement using a technique called a nested control flow. This is the process of putting a control statement inside of another control statement to execute an action. You can put an if statements inside for loops.

How do you write a loop condition?

The general loop algorithm works like this: Run begin → (if condition → run body and run step) → (if condition → run body and run step) → (if condition → run body and run step) → ... That is, begin executes once, and then it iterates: after each condition test, body and step are executed.

What is a conditional loop in C#?

C# provides the while loop to repeatedly execute a block of code as long as the specified condition returns true . Syntax: While(condition) { //code block } The while loop starts with the while keyword, and it must include a boolean conditional expression inside brackets that returns either true or false.


2 Answers

It is best practice to use a variable when you use the same statement more than once.

Here, nodes.Count is used in two places as below and hence, variable was used instead of executing the same statement twice.

for (int i = 0, n = nodes.Count; i < n; i++) {

And,

newNodes = new Expression[n];

Note: As discussed in the comments, performance difference is completely negligible though.

like image 87
Aruna Avatar answered Oct 23 '22 01:10

Aruna


I don't think it has any much performance effects in this case. But as they are using this n is this line as well,

newNodes = new Expression[n];

So,

  • Program has to get node.Count only once.
  • n need not to be assigned again.
  • Looks much cleaner.

That's all there is to it.

like image 2
Prajwal Avatar answered Oct 23 '22 02:10

Prajwal