Bug 8873 – Some class field reordering for emplacing?

Status
NEW
Severity
enhancement
Priority
P4
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2012-10-22T15:14:21Z
Last change time
2024-12-13T18:01:52Z
Assigned to
No Owner
Creator
bearophile_hugs
Moved to GitHub: dmd#18478 →

Comments

Comment #0 by bearophile_hugs — 2012-10-22T15:14:21Z
According to the specs D classes are free to reorder their fields: >The D compiler is free to rearrange the order of fields in a class to optimally pack them in an implementation-defined manner.< So in this program 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 bytes pragma(msg, __traits(classInstanceSize, Bar2)); // 20 bytes pragma(msg, __traits(classInstanceSize, Bar3)); // 20 bytes } 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 (because of the GC, it allocates 32 bytes for each class instance of Bar1, Bar2 or Bar3), 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; }
Comment #1 by bearophile_hugs — 2012-10-31T03:52:11Z
See also this related thread: http://forum.dlang.org/thread/[email protected] One of the questions of that thread look like a documentation enhancement request, by Peter Summerland: > The order of the fields is rearranged for packing. Does that > affect the tupleof property? The example in > http://dlang.org/class.html for Class properties tulpleof seems > to implie that the the fields the returned Expression Tuple are > arranged in lexical order (i.e., as defined by the programmer in > the class definition). Is this always true for classes?
Comment #2 by robert.schadek — 2024-12-13T18:01:52Z
THIS ISSUE HAS BEEN MOVED TO GITHUB https://github.com/dlang/dmd/issues/18478 DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB