Radoslav.Ivanov Radoslav.Ivanov - 5 days ago 4
C# Question

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

I've been digging through

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
?

Answer

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.

Comments