You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+28Lines changed: 28 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -33,6 +33,34 @@ Let us also mention original projects handling this task and without which this
33
33
-[maligned](https://github.com/mdempsky/maligned) from **Matthew Dempsky**
34
34
-[structslop](https://github.com/orijtech/structslop) from **orijtech**
35
35
36
+
## Deep dive
37
+
38
+
There are two main tasks that `betteralign` does:
39
+
40
+
1. Create a candidate layout order by sorting fields by **descending alignment** required (reducing holes/padding between struct fields),
41
+
2. Reduce **pointer bytes scanned** by GC ([GC will stop scanning values](https://go.dev/doc/gc-guide) at the last pointer in the value).
42
+
43
+
So having in mind those two tasks, field sort is performed the following way:
44
+
45
+
1.**Zero sized** objects are placed before non-zero sized objects,
46
+
2. More **tightly aligned** objects are placed before less tightly aligned objects,
47
+
3.**Pointerful objects** are placed before pointer-free objects,
48
+
4. If both objects have pointers, objects with less **trailing non-pointer objects** are placed earlier,
49
+
5. Lastly, order by **size**.
50
+
51
+
In case of the following:
52
+
53
+
```golang
54
+
package foo
55
+
56
+
typeIPAddrstruct {
57
+
Zonestring// 16 bytes, 8-byte aligned
58
+
IP []byte// 24 bytes, 8-byte aligned
59
+
}
60
+
```
61
+
62
+
Reason why `Zone` gets to be the first field is because trailing data comparison: `Sizeof(string) - ptrdata(string) = 8` vs `Sizeof([]byte) - ptrdata([]byte) = 16`, causing `string` field type to go first in struct `IPAddr` having less trailing non-pointer data.
0 commit comments