Vector Math Class Storage: Array vs. Separate Members

Started by
16 comments, last by Ectara 11 years, 4 months ago
It is my understanding that

struct myStruct{
int x, y, z;

int operator [](int index){
return (&x)[index];
}
}
myStruct s;
s.x = 0;


and


struct myStruct{
int a[3];

int operator [](int index){
return a[index];
}

int x(void){
return a[0];
}

int y(void){
return a[1];
}

int z(void){
return a[2];
}
};

myStruct s;
s.a[0] = 0;


are nearly equivalent in terms of speed on modern compilers. The problem arises when I need to access it by subscript, and also use it like an array of floats (like with OpenGL). However, which is more tedious to use:

1. Ensuring that every platform supports telling the compiler how to align and pad the members so that one can make an unsafe cast of the address of the first member to a pointer type, so that it can be subscripted or returned, and being able to refer to each member by their name

or

2. Storing the members as an array, allowing me to return a pointer and subscript safely and reliably, and providing an inlined x(), y(), and z() member function that returns a[0], a[1], and a[2] respectively

?

I'd prefer the second, as deterministic type safety seems like a better choice.

The downfalls of each, as far as I can tell:

1. Requiring alignment and padding to both be controlled the same way no matter what compiler (if the compiler can't or doesn't do it right, the program could crash!), and unsafe cast from a single member to a pointer of its type, knowing it will be accessed like an array.

2. Takes a couple more keystrokes to access the data (s.a[0] or s.x() vs s.x), and a little tougher to conceptually grasp.

I believe that a properly inlined s.x() or s.a[0] would be just as fast/slow as s.x; both would dereference a this pointer, and both would use a constant offset from the beginning of the struct (and possibly array) to reach the data, so it seems like it makes no difference in speed.

The pros of each:

1. Simple to use and understand; behaves how you expect a vector class might.

2. Performs reliably, and safely.

Which would be preferable, knowing that my goal is portability, and reliability (I'd rather not depend on compiler pragmas, macros, and settings)? Does the array method have any serious implications, like speed?
Advertisement
I think either method would work fine, and in practice you wouldn't have to worry about things like padding or alignment. The standard only guarantees that method 2 would work. Whether that's important to you is mostly a matter of personal preference.

I think either method would work fine, and in practice you wouldn't have to worry about things like padding or alignment. The standard only guarantees that method 2 would work. Whether that's important to you is mostly a matter of personal preference.

I plan to use SSE or whichever intrinsics are available if the processor has it, so there's a chance that the data must be non-padded and 16 byte aligned to use SSE, for example. Sounds like method 2 is the way to go for me; I try to go for standards compliance when possible.
int's cannot require padding. The platform is busted if that happens.
If you are concerned about a hidden forth int being added to providing padding for an array of points, that can/would happen with both structures.
Alignment might be an issue but it would be the same in both cases as well.

For both structures you need to set the packing to 0.

In the x,y,z case the compiler is free to rearrange the elements but I've never seen it happen for like-types and you can typically turn that off with a similar the setting/pragam mechanism that you set the packing with.
- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara

int's cannot require padding. The platform is busted if that happens.


In the x,y,z case the compiler is free to rearrange the elements but I've never seen it happen for like-types and you can typically turn that off with a similar the setting/pragam mechanism that you set the packing with.

Section 9.2.12:
"Nonstatic data members of a (non-union) class declared without an intervening access-specifier are allocated so that later members have higher addresses within a class object. The order of allocation of nonstatic data members separated by an access-specifier is unspecified (11.1). Implementation alignment requirements might cause two adjacent members not to be allocated immediately after each other; so might requirements for space for managing virtual functions (10.3) and virtual base classes (10.1)."

Unless an access-specifier intervenes between x, y, and z, they must all be in order of declaration. Additionally, it explicitly states that adjacent members might not be allocated immediately after each other, and makes no mention of any types. It's possible that ints could have no padding, or 1024 bytes. I wouldn't want to program on such a system, but it's possible.

The int type was a placeholder, as the actual datatype was irrelevant; I'll use a generic class name from now on. I was more concerned about the difference in ease of use between the two; having them all be separate members allows the compiler to do several of numerous unpredictable things that could break the code in porting it to another platform. Thus, I decided to go with the array of values, to ensure that each value will positioned immediately after the previous.

The alignment is already taken care of through means outside of the scope of this example.
Ah, I've held onto this link for many years, for just such an occasion.
In this thread you'll find the perfect answer I believe. You can have your cake and eat it too...
http://www.gamedev.net/topic/261920-a-slick-trick-in-c/
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms
Knowing 9.2.12 guarantees order of like-types you can accomplish this with a few lines of code.
If you make them templates you can toss the static back in if you want to force an instantiation.
I think that would be better in an explicit source file though (i.e. it's clear which object file it's in not in multiple!)

[source lang="cpp"]
struct v3
{
float x,y,z;
const float& operator[](int i) const { return (&x); }
float& operator[](int i) { return (&x); }
}
struct v4
{
float w,x,y,z;
const float& operator[](int i) const { return (&w); }
float& operator[](int i) { return (&w); }
}
[/source]
- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara

Knowing 9.2.12 guarantees order of like-types you can accomplish this with a few lines of code.
If you make them templates you can toss the static back in if you want to force an instantiation.
I think that would be better in an explicit source file though (i.e. it's clear which object file it's in not in multiple!)

[source lang="cpp"]
struct v3
{
float x,y,z;
const float& operator[](int i) const { return (&x); }
float& operator[](int i) { return (&x); }
}
struct v4
{
float w,x,y,z;
const float& operator[](int i) const { return (&w); }
float& operator[](int i) { return (&w); }
}
[/source]

I've seen this solution, before, and despite it looking fancy, it ignores what was also stated above "Implementation alignment requirements might cause two adjacent members not to be allocated immediately after each other; so might requirements for space for managing virtual functions (10.3) and virtual base classes (10.1)." It may be implementation defined to have 4 byte int members aligned to 8 byte boundaries. Such a machine that requires it would be inefficient, but that makes no difference in the fact that the standard allows for an implementation that would cause this example to break. Thus, I've avoided it.

The most important thing that has caused me to make my decision to use the array method is having the guaranteed that there will be no padding between elements in the array; it's not the first time I've made this decision.

However, there's now another reason: a lot of this code is designed to be parallelized, and the approach I'm using requires the members be in union with an aligned SIMD datatype, __m128. The most common solutions are:

struct myStruct{
union {
struct { int x, y, z; };
__m128 v;
};

...
}


and


struct myStruct{
union {
int a[4];
__m128 v;
};

...
}


The issue arises where the generic templated class would use either of the implementations outlined in my OP, but the SSE version would use either of these specialized implementations. The thing is, anonymous structures are not standards compliant! C11 just now added support for it, but C++11 still has no support for it. Anonymous unions are explicitly allowed, but there is no mention of anonymous structs. Thus, in order for this to comply with standards, the specialization with the union must contain a named object of the inner structure's type. However, to have this be consistent with the generic version, the generic version must contain an unnecessary inner structure containing the members. Thus, you lose all benefit of less keystrokes and a simpler concept, because the concept just became more obfuscated in order to comply with standards!

So, in conclusion, you can either have code that works some of the time, in some circumstances, on certain compilers, or have code that is more guaranteed to work the way you expect by abiding by the rules. The individual member method works so long as there are no specializations that require the members to be in a union (and aligned and unpadded, in this case), and you either use a switch, or load a temporary array with the values and subscript it in the subscript operator. Otherwise, you take a trip through implementation-defined behavior land.

I've seen this solution, before, and despite it looking fancy, it ignores what was also stated above "Implementation alignment requirements might cause two adjacent members not to be allocated immediately after each other; so might requirements for space for managing virtual functions (10.3) and virtual base classes (10.1)." It may be implementation defined to have 4 byte int members aligned to 8 byte boundaries. Such a machine that requires it would be inefficient, but that makes no difference in the fact that the standard allows for an implementation that would cause this example to break. Thus, I've avoided it.


What's harder to imagine is an architecture that would require alignment of members of the same type different from the alignment required of elements in an array. That's why I said that they will both work in practice.

If you worry that your compiler might put an infinite loop before returning from main because the standard allows it (at least that's my reading of the section on "observable behavior"), then you may also worry about a compiler putting padding between members of the same basic type. Otherwise, not really something to stress about.

Ah, I've held onto this link for many years, for just such an occasion.
In this thread you'll find the perfect answer I believe. You can have your cake and eat it too...
http://www.gamedev.n...ick-trick-in-c/

The content looks interesting, but I'm having a hard time understanding how the pointer array winds up pointing to the actual data, unless I'm misreading it.

This topic is closed to new replies.

Advertisement