How to concatenate two lists efficiently?

0

With the purpose of the union represented by the figure:

Given the structure below:

TMyRecord = record
    Index: Int64;
    Kind: TMyEnum;
    Value: String;
end

Having two lists ( Generics.Collections.TList<TMyRecord> ) A and B I use the following method to perform the join:

ListA.AddRange(ListB.ToArray);
ListA.TrimExcess;

The problem with this method is that it results in poor performance for lengths over 400 elements per list.

Another requirement would be to maintain the order where after the last element of A must meet the first of B. Such ordering would make it difficult to use parallelism.

So, what are some effective ways of achieving unity by ensuring performance and ordering?

    
asked by anonymous 23.03.2016 / 20:49

1 answer

0

I could not reproduce poor performance with 3,000 items per list. Also the order is being maintained. I think other things are interfering with your code.

See the code below:

program Project2;

{$APPTYPE CONSOLE}

uses
  SysUtils, Generics.Collections, Diagnostics;

type
  TMyEnum = (meUno, meDuo, meFoo, meBar);

  TMyRecord = record
    Index: Int64;
    Kind: TMyEnum;
    Value: String;
  end;

  TMyLista = Generics.Collections.TList<TMyRecord>;


const
  TamanhoCadaArray = 3000;

var
 ListaA,ListaB: TMyLista;
 ts1: TStopwatch;

procedure PreencheLista(Lista: TMyLista; const nn:string);
var
  I: Integer;
  myRec: TMyRecord;
begin
  for I := 1 to TamanhoCadaArray do
  begin
    myRec.Index := I;
    myRec.Kind := tmyenum(I mod 4);
    myRec.Value := nn+ ' '+ IntToStr(I);
    Lista.Add(myRec);
  end;

end;

begin
  try
    ListaA := TMyLista.Create;
    ListaB := TMyLista.Create;

    PreencheLista(ListaA, 'A');
    PreencheLista(ListaB, 'B');

    ts1.Create;
    ts1.Start;
    ListaA.AddRange(ListaB.ToArray);
    ListaA.TrimExcess;
    ts1.Stop;

    Writeln(ts1.Elapsed.TotalMilliseconds);
    Writeln(ListaA[0].Value);
    Writeln(ListaA[1].Value);
    Writeln(ListaA[2].Value);
    Writeln(ListaA[3].Value);
    Writeln(ListaA[4].Value);

    Writeln(ListaA[TamanhoCadaArray].Value);
    Readln;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.
    
28.03.2016 / 16:09