Reordered class fields?
bearophile
bearophileHUGS at lycos.com
Sun Oct 21 16:36:02 PDT 2012
D classes are free to reorder their fields, so maybe Bar1 should
reorder its fields as Bar3, to save 4 bytes for each instance on
32 bit systems:
class Bar1 {
void Hello() {}
float f;
double d;
}
class Bar2 {
void Hello() {}
align(4) float f;
align(4) double d;
}
class Bar3 {
void Hello() {}
double d;
float f;
}
void main() {
pragma(msg, __traits(classInstanceSize, Bar1)); // 24
pragma(msg, __traits(classInstanceSize, Bar2)); // 20
pragma(msg, __traits(classInstanceSize, Bar3)); // 20
}
This benchmark shows that if you allocate the class instances on
the heap one at a time the total amount of memory used is the
same for the various Bar (maybe because of the GC), so that
optimization is useful for emplace() only and similar in-place
allocations:
class Bar1 {
void Hello() {}
float f;
double d;
}
class Bar2 {
void Hello() {}
align(4) float f;
align(4) double d;
}
class Bar3 {
void Hello() {}
double d;
float f;
}
int main() {
pragma(msg, __traits(classInstanceSize, Bar1)); // 24
pragma(msg, __traits(classInstanceSize, Bar2)); // 20
pragma(msg, __traits(classInstanceSize, Bar3)); // 20
//--------------
//auto arr = new Bar1[1_000_000]; // 38.2 MB
//auto arr = new Bar2[1_000_000]; // 38.2 MB
auto arr = new Bar3[1_000_000]; // 38.2 MB
foreach (ref a; arr)
a = new typeof(arr[0])();
int count;
foreach (i; 0 .. 500_000_000) count++;
return count;
}
So is such class field reordering worth an enhancement request in
Bugzilla?
Bye,
bearophile
More information about the Digitalmars-d-learn
mailing list