On this page

0031. Unions use a tagged C union

Context

M4.3 lowers enum values to C. Two layouts were candidates (EXPERIMENTS.md, CP-4.1 union-layout): A, a uint32_t tag plus a C union of one payload struct per variant; B, a uint32_t tag plus every variant's payload struct side by side with no overlap. B's hypothesis was that it matches A's speed and avoids any union-read warning. Values are passed by value (no pointers before M5), so sizeof is paid on every copy, call and return.

The experiment generated equivalent C for both layouts and timed it with gcc -std=c11 -Wall -Wextra -O2, 7 runs each (median and min), at default alignment and with -falign-functions=32. Outputs were byte-identical between layouts; neither layout produced any gcc warning.

Workload Align Layout sizeof Median s Min s
small (3 variants, ≤3 fields) default A 32 0.632 0.552
small default B 56 0.493 0.343
small align 32 A 32 0.568 0.522
small align 32 B 56 0.469 0.285
wide (8 variants, ≤6 fields) default A 56 0.978 0.960
wide default B 200 2.964 2.842
wide align 32 A 56 1.033 0.961
wide align 32 B 200 2.929 2.872
pipeline (4 variants, array round trip) default A 32 0.788 0.771
pipeline default B 56 1.308 1.255

Decision

Keep layout A: a uint32_t tag and a C union of per-variant payload structs, as M4.3 emits it. The plan's rule was to adopt B only if it was at least 10% faster in 2 of 3 workloads under both alignments with sizeof at most 2×. B won only the smallest workload, lost wide by 3.0× and pipeline by 1.7×, and grew wide's sizeof 3.6×. The experiment is closed.

Alternatives considered

Consequences