5

I have a 3D vector class. The private variables are defined:

union {
    struct {
        double x;
        double y;
        double z;
    };
    double data[3];
};

In implementing operator==, which is faster?

return this->x == v.x && this->y == v.y && this->z == v.z;

OR

return memcmp(this->data, v.data) == 0;
Anthony
  • 12,177
  • 9
  • 69
  • 105
  • I used the union so I can just pass `data` to 3rd party APIs that require a `double*`. – Anthony Jun 22 '10 at 03:21
  • @Stephen - directly memcmp-ing a structure can be risky. If the compiler puts in padding, the structures may be different even though all the fields are the same. – R Samuel Klatchko Jun 22 '10 at 03:24
  • @R Samuel : Thanks, good point. _comment withdrawn._ :) – Stephen Jun 22 '10 at 03:33
  • 1
    Here's another thing to consider about performance, especially considering 3D graphics: Chances are, if you are asking about performance, you still have a lot to learn before you'll be truly *efficient*. There is such an astounding amount of knowledge required in that space, that you're probably better off just making everything clean and functional until you have a 100% working program. Then you can try tweaking and optimization, delving into assembler, clock-tick measurements, and all sorts of fun compiler flags! – Tom Jun 22 '10 at 04:29

1 Answers1

15

Unfortunately the two aren't equivalent. (Specifically NaNs and signed zeros don't use bitwise comparison inside the FPU).

So you should make your choice based on correctness, not speed.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • 1
    Right, I just completely forgot about that. Rookie mistake I suppose. – Anthony Jun 22 '10 at 03:23
  • 1
    @Duracell: The rookie mistake is worrying about performance over good code. :) Performance is your last concern. – GManNickG Jun 22 '10 at 03:36
  • 1
    @GMan: You could say that, but I'd completely overlooked the fact that memcmp wouldn't work. Without that, I'd assumed my code was good and could therefore look at speed. – Anthony Jun 22 '10 at 03:43
  • OK @Ben Voigt, with that out of the way, what if the vectors just used ints? And I know all about the "Don't prematurely optimize!!!!1" argument. I'm just interested to know. – Anthony Jun 23 '10 at 05:54
  • ints use bitwise comparison. Actually, using bitwise comparison on doubles is not necessarily a bad thing, *if you don't want IEEE handling of NaN values*. For example, using IEEE comparisons can result in the following: `bool func(vector a) { vector b = a; return b == a; }` returning `false` (in the case of quiet NaNs) or even crashing (in the case of signalling NaNs). – Ben Voigt Jun 23 '10 at 12:32
  • Thanks, I thought that was the case. – Anthony Jun 24 '10 at 22:34