DelphiBasics
Packed
Keyword
Compacts complex data types into minimal storage
 keyword Packed(type Name = Packed array[...] of ...;
 type Name = Packed class ... end;
 type Name = Packed object ... end;
 type Name = Packed record ... end;
Description
The Packed keyword tells Delphi to minimise the storage taken up by the defined object.
 
Normally, complex data types, such as records have their elements aligned to 2, 4 or 8 byte boundaries, as appropriate to the data type. For example, a Word field would be aligned to a 4 byte boundary.
 
Records are also padded to ensure that they end on a 4 byte boundary.
 
These alignments ensure optimal access performance.
 
The Packed overrides this, compressing the data into the smallest storage, albeit with consequential reduced access performance.
Notes
Examples of unpacked alignments :

Word     = 2 bytes
LongWord = 4 bytes
Single   = 4 bytes
Double   = 8 bytes

Related commands
$AlignDetermines whether data is aligned or packed
ArrayA data type holding indexable collections of data
ClassStarts the declaration of a type of object class
ObjectAllows a subroutine data type to refer to an object method
RecordA structured data type - holding fields of data
 Download this web site as a Windows program.




 
Example code : Packing a record to reduce storage
type
  // Declare an unpacked record
  TDefaultRecord = Record
    name1   : string[4];
    floater : single;
    name2   : char;
    int     : Integer;
  end;

  // Declare a packed record
  TPackedRecord = Packed Record
    name1   : string[4];
    floater : single;
    name2   : char;
    int     : Integer;
  end;

var
  defaultRec : TDefaultRecord;
  packedRec  : TPackedRecord;

begin
  ShowMessage('Default record size = '+IntToStr(SizeOf(defaultRec)));
  ShowMessage('Packed record size = '+IntToStr(SizeOf(packedRec)));
end;
Show full unit code
  Default record size = 20
  Packed record size = 14
 
Delphi Programming © Neil Moffatt . All rights reserved.  |  Home Page