Thursday, January 29, 2015

New dynamic array type in Spring4D 1.2

Today I want to talk about dynamic arrays. Often you might prefer them over a full blown generic list because it avoids creating an instance just to store a couple of elements (which are backed by a dynamic array inside the list anyway - at least for a regular TList<T> regardless if you use those from the RTL or the Spring4D ones).

But they are tedious to use even with the additional syntax support in Delphi XE7. There are other implementations that improve dynamic array usage that work even for older versions.

Spring4D will introduce the new DynamicArray<T> type which is a record type with several methods and operator overloads (take a look at it in our develop branch on Bitbucket where we are busy implementing a lot of awesome things for Spring4D 1.2 release this spring).

Let's take a quick look at some of the code you can write using the new DynamicArray<T>.

  arr, arr2: DynamicArray<Integer>;
  i: Integer;
  arr := [1, 2, 3];
  arr := arr + arr;
  arr := arr + [4, 5];
  arr.Assign([1, 2, 3]);
  arr.Add([4, 5]);
  for i in arr do
    Write(i, ' '); // 1 2 3 1 2 3 4 5

  arr2.Assign([2, 4]);
  if arr2 in arr then
    arr := arr - arr2;
    for i in arr do
      Write(i, ' '); // 1 3 1 2 3 5

  arr.Assign([1, 2, 3, 4, 5, 6]);
  arr2 := arr.Splice(2, 2, [7, 8, 9]);
  for i in arr2 do
    Write(i, ' '); // 3 4
  for i in arr do
    Write(i, ' '); // 1 2 7 8 9 5 6

It will be available in all versions supported (Delphi 2010 and higher) - only the new syntax to initialize a dynamic array (with the square brackets) is limited to XE7 and higher. But DynamicArray<T> has the add operator and even some more that you don't have with native XE7 dynamic arrays. All methods are continuously optimized for performance as far as possible using pure pascal. DynamicArray<T> does not perform any worse than using the native operations - in some situations even better. Of course it is assignment compatible to TArray<T> by implicit operator overload and will run on all platforms.

Until next time with more about Spring4D 1.2 or something different but not any less interesting!

Edit (01.02.2015): renamed TDynArray to DynamicArray<T>

No comments:

Post a Comment