简体   繁体   中英

Rewrite the following code to have the arithmetic performed only once, even if the loop executes 1,000 times?

So I'm reading a programming book and it had this question written:

How could you rewrite the following code to have the arithmetic performed only once, even if the loop executes 1,000 times?

while (x < a + b)
// loop body

The correct answer is this:

int sum = a + b;
while(x < sum)
// loop body

I'm really not understanding the logic here....Can someone explain this answer to me? Because this doesn't make sense to me at all.

In the first version of the loop:

while (x < a + b)
// loop body

The sum a + b is calculated during each iteration of the loop. If the sum is independent of the loop and never changes, then this is wasteful. So one option for efficiency is to compute this sum outside the loop as in the second version:

int sum = a + b;
while(x < sum)
// loop body

I would expect that a good Java or C compiler would be able to detect this on its own, and make this optimization automatically.

In the first example, the while condition ( x < a + b ) is tested every time the loop runs. This causes the program to calculate a + b every time the condition is tested. In the second example, a + b is calculated before the while loop is executed so the condition test doesn't have to do it every time.

Assumption: neither a nor b are modified in the loop body

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM