开发者

Is a function within the loop-test portion of a FOR loop called on every iteration?

开发者 https://www.devze.com 2023-02-03 13:37 出处:网络
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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消