Reputation: 433
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
?
Upvotes: 7
Views: 511
Reputation: 12022
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.
Upvotes: 11
Reputation: 4000
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.
Upvotes: 2