user11634612
user11634612

Reputation:

Using Unions vs Multiple structs

I am quite new in c++, sometimes i am not sure what is better way performance/memory. My problem is that i need struct with exactly two pointers to vec3 (3 floats) and vec3/vec2.

Right now i am trying to decide if use: - Unions with two constructors, one for vec3 and one for vec2 - Create two structs , one will contain vec2 and one vec3

struct vec3
{
    float x,y,z;
};
struct vec2
{
    float x,y;
};
struct Vertex
{
    template <typename F>
    Vertex(vec3 *Vertices,F Frag)
    : m_vertices(Vertices),m_fragment(Frag)
    {}

    union Fragment
    {
        Fragment(vec3 *Colors)
        :colors(Colors)
        {}
        Fragment(vec2 *Texcoords)
        :texcoords(Texcoords)
        {}

        vec3 *colors;
        vec2 *texcoords;

    } m_fragment;


    vec3 * m_vertices;
}

This code works well, but i am quite worried about performance, as i intend to use Vertex struct very often, my program might have thousand of instances of Vertex struct.

Upvotes: 2

Views: 198

Answers (1)

Miles Budnek
Miles Budnek

Reputation: 30494

If every Vertex can have either colors or texcoords, but never both, then a union (or better yet, a std::variant<vec3, vec2>) makes sense.

If a Vertex can have both colors and texcoords, then a union won't work, since only one member of a union can be active at a time.

As for performance, profile, profile, profile. Build your interface in such a way that the choice of union or separate members is invisible to the caller. Then implement it both ways and test to see which performs better (or if there's a perceptible difference at all).

Upvotes: 2

Related Questions