Pages, some stolen, some original

Sunday, October 9, 2016

Optimization

I'm playing with some code over at Coding Game dot com, and I write a couple of equations:

    p1.x += abs(p1.x - p2.x) * d1 / d2
    p1.y += abs(p1.y - p2.y) * d1 / d2

Both equations use the expression d1/d2 (the slash means divide). Division is kind of an expensive operation in terms of machine cycles, so if execution speed mattered then we would not want to be repeating this operation. Instead we would perform the division once and save the result, like this:

    temp = d1 / d2
    p1.x += abs(p1.x - p2.x) * temp
    p1.y += abs(p1.y - p2.y) * temp

But compilers have gotten pretty smart, or rather compilers are written by some pretty smart people, and it's entirely possible that the compiler would have recognized the duplicate operation and saved the result automatically, which would negate the need for our adding the extra statement.

I was thinking about posting this question on Stack Overflow, but after looking around a bit I realized it might depend on which version of which compiler is being used, and what options (switches) were chosen when the compiler was invoked, and does it really make any difference anyway? I mean if we were really serious about this we would be running tests to see how long this operation takes and comparing that to our requirements. Then, if we found this bit of code to be critical to our success, we would open up the debugger and look at the machine code (assembly language) and see whether adding a statement made any difference. And then it might very well depend on whether you were optimizing for speed or space.

Since it is unlikely this one operation is going to make any difference in the outcome of this program, I have opted to stick with original pair of statements. It only takes two lines of text, not three, and it should be obvious to the most casual observer that the two statements perform the same operation. Line one operates on the x coordinate, line operates on the y. Adding the extra statement only confuses the issue, and clarity is the most important attribute of any computer program.



No comments:

Post a Comment