Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Sneaky Internal State

Name: Anonymous 2012-03-28 23:59

I've boiled what I want out of a programming language down to a single example.  Problems like this bite me in the ass often and I haven't used a language, yet, that helps.

Suppose I'm writing a library for working with vectors.  For simplicity, it's not fancy n-dimensional vectors, etc., let's say just three floats.  So I write some code to perform operations on vectors, like add, subtract, dot product, cross product, rotate, scale... and then I come to "normalize."

Here, I come up with this optimization that vectors could also store a flag indicating whether or not they are normal.  If that flag is set, then normalize has no work to do.  The catch is that I have to decide which operations clear the flag, which operations set it, and which operations leave it unchanged.  So I do the work and end up with a nice, efficient vector library.

I use my library for a long time -- long enough that I stop caring how that optimization worked.  Eventually, months later, I decide to add some new functions to my vector library.  Of course, I've forgotten all about the "normal" flag, and I forget to set/clear it in the new functions.  Of course, there's no compile error or even a run-time error.  I just observe strange behavior when the application runs and I have to spend hours stepping through floating-point math to figure out what's wrong.

How does your language of choice improve this situation?

Name: Anonymous 2012-03-29 1:41

>>13
It's fucking shit. When adding two arbitrary vectors, they will almost never result in a unit length vector. That means that the flag will almost always be false, meaning your optimized code will almost always do an unneeded check against a boolean flag, before observing that it is false and then proceed to perform the square root you seek to avoid. By adding checks like this, you increase the cost of the worst case behavior, and if the worst case behavior almost always happens, you are just slowing shit down. It doesn't matter if it saves you time a couple times if it slows shit down 200 million other times. But if it just happens that you are always adding two parallel vectors with magnitudes that sum to one, then a really cool compiler might be able to detect that, and inline that optimization into the generated code, and throw away the normalization for that case. But until you have such a thing at your disposal, you are better off hand coding these optimizations in the code.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List