"Gary Wessle" <ph****@yahoo.c omwrote in message
news:m3******** ****@localhost. localdomain...
Hi
I read some where about the order variables are declared in a class
may help space optimization.
find the size of bits a variable takes and declare them from biggest
to the lowest.
so in my system that would be.
double
int
string
char
bool
is the principle correct? if so, then at the top of the list should be
things like
vector<double>
vector<int>
...
and same for map(s) and so on...
but what about function declaration?
where do then fit, what is the size of a function declaration?
thanks
Yes and no. Consider a structure (or class) such as:
class MyClass
{
char Char1;
int Int1;
char Char2;
};
What is the size of that class?
(on my system with sizeof int being 4)
Well, the compiler will allocate one byte for the char, then skip 3 bytes so
the int is aligned properly, then 4 bytes for the int, then 1 byte for the
second char, then skip 3 more bytes so an array of this class will be
aligned properly. So 12 bytes, when only 6 are actually used.
So we can arrange it and make the largest first so it would become:
class MyClass
{
int Int1;
char Char1;
char Char2;
};
What's the size of this class?
4 bytes for the int, 1 byte for the first char, 1 byte for the 2nd char,
skip 2 bytes for alignment. 8 bytes total.
But we get the same result with:
class MyClass
{
char Char1;
char Char2;
int Int1;
};
1 byte, 1 byte, skip 2, 4 bytes.
Generally, the compler will align a type on it's size. If a variable is 4
bytes, it will align it every 4 bytes. 2 bytes, 2, etc... I said
generally, there may be exceptions with OS/compilers/CPUs, etc...
As long as you understand what's going on it should be relatively easy to
figure out how to get rid of wasted space. I.E. This is extremly wasteful:
class MyClass
{
char Type1;
int Val1;
char Type2;
int Val2;
char Type3;
int Val3;
};
24 bytes.
A little rearranging:
class MyClass
{
char Type1;
char Type2;
char Type3;
int Val1;
int Val2;
int Val3;
};
16 bytes. I could of put the ints first.
However, I tend to arrange my class variables on their usage, grouping like
with like. Just use a little common sense and things should be fine.