In Agner Fog's "Optimizing software in C++" it is stated that union forces a variable to be stored in memory even in cases where it otherwise could have been stored in a register, which might have performance implications. (e.g. page 148)
I often see code that looks like this:
struct Vector {
union {
struct {
float x, y, z, w;
};
float v[4];
}
};
This can be quite convenient, but now I'm wondering if there might be potential performance hit. I wrote a small benchmark that compares Vector implementations with and without union and there where cases where the Vector without union apparently performed better, although I don't know how trust-worthy my benchmark is. (I compared three implementations: union; x, y, z, w; v[4]. For example, v[4] seemed to be slower when passed by value, although the structs all have the same size.)
My question now is, whether this is something that people consider when writing actual production code? Do you know of cases where it was decided against unions specifically for this reason?