Free Pascal

Bit-packed structure (record) in Free Pascal and Delphi

Here is the code explaining some methods to pack bit accessing logic in your program.

program project1;
 
type
  TRec1 = packed record // Doesn't pack at all
    b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16: boolean;
  end;
 
  TRec2 = bitpacked record // Free Pascal specific
    b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16: boolean;
  end;
 
  TRecByte = (b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16);
  TRecBytes = set of TRecByte;
var
  r1: TRec1;
  r2: TRec2;
  s1: TRecBytes;

Sorted map vs hashed map

In theory, hash map structure should be very fast on retrieving by key operations, close to O(1) like for an array. A sorted map (keys are sorted) should be O(log2 N) instead. The following test checks the difference.

Common scenario

We will use one tester class per type of tested structure. The keys are string[10] and are generated randomly in prepared array to avoid additional checks whether the key exists or not.

Why need to specify unit names?

In the previous article "Crack C# namespaces in 30 seconds" I demonstrated how to make error having no idea about it. So you will have a lovely time in debugging. But in C# you're condemned to use using directive or your code will be unreadable with all these horrible specifiers MySolution.AppModules.Accounting.AccountingType.DefaultValue.

Free Pascal bencmark: array vs TList vs dynamic array

Let's make a simple benchmark test for random and sequential access. I will compare:

  • array with predefined size (allocated on stack)
  • TList container class (allocated on heap)
  • dynamic array (allocated on heap)
  • generic TFPGList (allocated on heap)

I use an array of 10M elements having integer and varaint data type. You can easily change its type definition in "type" section if need.

Subscribe to RSS - Free Pascal