ihoaxed - 5 months ago 14x

Java Question

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.

Answer

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.

Source (Stackoverflow)

Comments