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
?
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.
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.
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.
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.
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,
node.Count
only once.n
need not to be assigned again.That's all there is to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With