2
votes

Point is opimization here.

Now:

type TSomeClass=class(TObject)
  private
    DataWrite: TBytes;
  ...
end;

Function TSomeClass.GetPacket: TBytes;
begin
  SetLength(Result, Length(DataWrite));
  Move(DataWrite[0],Result[0],Length(DataWrite));
end;

What I want to achieve:

Function TSomeClass.GetPacket: TBytes;
begin
  Result := DataWrite;
end;

Because Arrays in Delphi are pointers to first element, the latter only and only writes 4 bytes so it is MUCH faster. Is this correct?

2
do you want to copy the data or copy the reference? - David Heffernan

2 Answers

7
votes

The one thing you need to be aware of is that different from strings, dynamic arrays are not "copy-on-write".

If you assign a string, or a dynamic array, only the pointer to the data on the heap is copied and the reference count is incremented.

But with a string, if you then write into a string (e.g. s[1] := 'a') which has a reference count > 1, the compiler will emit code which makes sure that the string is copied first. This is not the case with dynamic arrays:

var 
  s, t: string;
  a, b: TBytes;
begin
  s := 'abc';
  t := s;
  t[2] := 'X';
  WriteLn(s); //still abc

  a := TBytes.Create(1, 2, 3);
  b := a;
  b[1] := 0;
  WriteLn(a[1]); // is now 0 not 2!

So in case of your code, if you change the contents of DataWrite after GetPacket was called, the change will be visible in the TBytes that GetPacket returned.

For the code where you actually make a copy of the array, instead of calling SetLength And Move, you can use:

function TSomeClass.GetPacket: TBytes;
begin
  Result := Copy(DataWrite, 0, High(Integer));
end;
2
votes

That will work but note that you are now working on the same byte array in client code that calls GetPacket. This might be a bad idea. Consider some network library that does some additional compression or encryption on the byte array. This creates a lot of possibilites to interact with your class without using the exposed interface - which is bad. Thus IMHO copying is the better option here.

BTW: How big are the arrays we are talking about here?