Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Just a quick question.

I have a loop that looks like this:

for (int i = 0; i < dim * dim; i++)

Is the condition in a for loop re-evaluated on every loop?

If so, would it be more efficient to do something like this?:

int dimSquare = dim * dim;
for (int i = 0; i < dimSquare; i++)

Thanks

-Faken

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
187 views
Welcome To Ask or Share your Answers For Others

1 Answer

Yes, semantically it will be evaluated on every loop. In some cases, compilers may be able to remove the condition from the loop automatically - but not always. In particular:

void foo(const struct rect *r) {
  for (int i = 0; i < r->width * r->height; i++) {
    quux();
  }
}

The compiler will not be able to move the multiplication out in this case, as for all it knows quux() modifies r.

In general, usually only local variables are eligible for lifting expressions out of a loop (assuming you never take their address!). While under some conditions structure members may be eligible as well, there are so many things that may cause the compiler to assume everything in memory has changed - writing to just about any pointer, or calling virtually any function, for example. So if you're using any non-locals there, it's best to assume the optimization won't occur.

That said, in general, I'd only recommend proactively moving potentially expensive code out of the condition if it either:

  • Doesn't hurt readability to do so
  • Obviously will take a very long time (eg, network accesses)
  • Or shows up as a hotspot on profiling.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...