If a function is part of the loop-test in a FOR loop, is that function cal开发者_Go百科led on every iteration of the loop or only the first iteration to setup the loop.
e.g.
for (i = 0; i < strlen(someString); i++) {
// Do Something
}
Is it better form to define a variable before the loop, whose value is the string length?
e.g.
int length = strlen(someString);
for (i = 0; i < length; i++) {
// Do Something
}
It depends on the language (and if there is a method call as part of the test, and whether the compiler can determine if the method call will not change each iteration)
For instance, in some situations VB.NET evaluates once, c# evaluates each time.
There was a recent SO question that illustrated this: Why does C# execute Math.Sqrt() more slowly than VB.NET?
Yes, the condition in a for loop is checked on every iteration. If the function you're calling there is at all expensive, then you should definitely store the value in a variable. However, if you have a short loop, it really won't make a difference.
精彩评论