Name

Packed Keyword

Syntax

type Name = packed record ... end;
type Name = packed class ... end;
type Name = packed object ... end;
type Name = packed array[...] of ...;

Description

Delphi aligns record and object fields on natural boundaries to improve performance. If you use the packed directive, Delphi does not insert any padding to align fields within the object or record.

An aligned record is also padded so its size is a multiple of 4 bytes. A packed record does not have any extra padding, but Delphi aligns and pads variables and dynamically allocated memory on 4-byte boundaries, so the size of a packed record is meaningful only if you are creating an array of records or using records as fields in other structured types.

The unpacked alignment for a field depends on the size of the field:

  • Byte-sized fields and sets of any size are aligned on byte boundaries.

  • Word-sized fields are aligned on word (2-byte) boundaries.

  • LongWord-sized fields (including Single) are aligned on long word (4-byte) boundaries.

  • Other types (Comp, Currency, Double, Extended, Int64, Real48, Variant) are aligned on 8-byte boundaries.

  • Arrays are aligned according to the alignment of the array’s base type.

  • Records are aligned according to the largest alignment used by a member in the record.

Tips and Tricks

  • Accessing a packed field is slower than accessing an aligned field. Use the packed keyword only when the need to conserve memory outweighs the performance penalty.

  • Delphi does not pack Boolean fields into single bits, the way some Pascal compilers do.

  • Arrays are always packed. You can supply the packed keyword in an array declaration for compatibility with standard Pascal, but it has no effect.

Example

type
  Big = record    // SizeOf(Big) = 16
    B1: Byte;
    W: Word;      // Align W on a word boundary by inserting a pad byte
    B2: Byte;
    L: LongWord;  // Align L on a 4-byte boundary by inserting 3 bytes
    B3: Byte;     // Record size is aligned to a long word boundary
  end;
  Small = packed record // SizeOf(Small) = 9
    B1: Byte;
    W: Word;      // Align W on a byte boundary: no padding
    B2: Byte;
    L: LongWord;
    B3: Byte;     // Record size is not padded.
  end;

See Also

Array Keyword, Class Keyword, Object Keyword, Record Keyword
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset