Packed: what changed
Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.
Title: Packed
| Old | New | Line | |
|---|---|---|---|
| 1 | + | The [[Reserved word|reserved word]] `packed` tells the compiler to use as little memory as possible for a particular complex data type. Without specifying `packed`, the compiler may insert extra unused bytes between members in order to align the data on full word boundaries for faster access by the CPU. | |
| 2 | + | ||
| 3 | + | ``` pascal | |
| 4 | + | program packedDemo(input, output, stderr); | |
| 5 | + | ||
| 6 | + | type | |
| 7 | + | signedQword = record | |
| 8 | + | value: qword; | |
| 9 | + | signum: -1..1; | |
| 10 | + | end; | |
| 11 | + | ||
| 12 | + | signedQwordPacked = packed record | |
| 13 | + | value: qword; | |
| 14 | + | signum: -1..1; | |
| 15 | + | end; | |
| 16 | + | ||
| 17 | + | begin | |
| 18 | + | writeLn(' signedQword: ', sizeOf(signedQword), 'B'); | |
| 19 | + | writeLn('signedQwordPacked: ', sizeOf(signedQwordPacked), 'B'); | |
| 20 | + | end. | |
| 21 | + | ``` | |
| 22 | + | ||
| 23 | + | So `packed` sacrifices some speed while reducing the memory used. | |
| 24 | + | ||
| 25 | + | ## Circumvention | |
| 26 | + | ||
| 27 | + | Smart ordering of record elements can mitigate the issue. In the example above `signedQword` as well `signedQwordPacked` have `signum` located at an offset of `8`. That is OK. If for any reason `value` and `signum` were listed in reverse order, `signum` would appear in both versions at an offset of `0`, but in the `packed` version `value` has an offset of `1` Byte. This might cause a potentially slower access to the `value` field. | |
| 28 | + | ||
| 29 | + | ## See also | |
| 30 | + | ||
| 31 | + | - [[sA|{$align}]] | |
| 32 | + | - [[sPack|{$pack}]] | |
| 33 | + | - procedures [`pack`](https://www.freepascal.org/docs-html/rtl/system/pack.html) and [`unpack`](https://www.freepascal.org/docs-html/rtl/system/pack.html) | |
| 34 | + | - [“Packing and unpacking an array” in § “Arrays” of the Reference Guide](https://www.freepascal.org/docs-html/ref/refsu14.html) | |
| 35 | + | - [[Bitpacked|bitpacked]] | |
| 36 | + | ||
| 37 | + | --- | |
| 38 | + | *From the Free Pascal wiki, page "Packed", as it stood on 2020-05-16 after a change by Kai Burghardt, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).* |
