Fabrizio
Fabrizio

Reputation: 8043

Which are differences between Variant arrays and dynamic arrays?

Which are differences between using a Variant array (Like shown here)

var
  VarArray : Variant;
begin
  VarArray := VarArrayCreate([0, 1], varInteger);
  VarArray[0] := 123;
  <...>
end;

instead of a common dynamic array?

var
  DynArray : array of Integer;
begin
  SetLength(DynArray, 1);
  DynArray[0] := 123;
  <...>
end;

Upvotes: 4

Views: 1305

Answers (1)

Rudy Velthuis
Rudy Velthuis

Reputation: 28806

Variants are a type that gets special handling from the compiler and the runtime. Under the hood, they are records of the type TVarRec. They can contain many different kinds of types internally, and can even be used to convert between some of these types. But they can also contain arrays of values, even arrays of other Variants, single- and multi-dimensional. That are Variant arrays. The System.Variants unit contains functions to define and handle such arrays.

Some more info on the Delphi Basics site.

Variants are typically used by Windows COM. Note that they can be pretty slow, especially Variant arrays with multiple dimensions. The number of types they can contain is limited.

Dynamic arrays are built-in types. They are normal arrays that can contain elements of any conceivable type, built-in or user defined. The difference with normal (static) arrays is that they can be instantiated, enlarged or shrunk dynamically (e.g. using SetLength), and their variables are pointers to the real array (which is allocated on the heap). Their lifetime is managed by the runtime.

Dynamic arrays are proper built-in types and far more general than Variants (and Variant arrays).

Delphi Basics also has more info on them.

Update

As Remy Lebeau commented, I should mention that a Variant array (and also an OleVariant array) is based on COM's SAFEARRAY structure, and thus can only be created with COM/OLE-compatible data types, even though Delphi's Variant can hold non-COM/OLE types.

Upvotes: 12

Related Questions