user401247
user401247

Reputation:

Recommended way to copy an open array

Other than using a for loop, what is the recommended way of copying the contents on one open array to another open array as quickly as possible? In this case the array is a simple array of doubles, you can assume that the source and target arrays have the same size.

myValues : array of double;

I saw an answer to this question How to copy array? which uses Move. Is this a reasonable approach to take or are there alternatives? Such copying will be done frequently so I am looking for the most efficient way.

Upvotes: 0

Views: 479

Answers (1)

David Heffernan
David Heffernan

Reputation: 613003

Although you ask about copying from one open array to another, I wonder if that's what you actually want to do. I suspect that you are actually using terminology rather loosely. The question that you link to covers copying an open array to a dynamic array. I assume that's what you really want to do.

If you know that the base type is unmanaged, and that a raw memory copy is valid, then you will struggle to beat the performance of Move. But only contemplate Move if performance of that part of your code is critical. Using untyped operations is best avoided unless there are compelling reasons to abandon the security of the type system.

For a general purpose array copy, I use this type:

type
  TArray = class(Generics.Collections.TArray)
  public
    class function Copy<T>(const Source: array of T; Index, Count: Integer): TArray<T>; overload; static;
    class function Copy<T>(const Source: array of T): TArray<T>; overload; static;
  end;

class function TArray.Copy<T>(const Source: array of T; Index, Count: Integer): TArray<T>;
var
  i: Integer;
begin
  SetLength(Result, Count);
  for i := 0 to high(Result) do begin
    Result[i] := Source[i+Index];
  end;
end;

class function TArray.Copy<T>(const Source: array of T): TArray<T>;
var
  i: Integer;
begin
  SetLength(Result, Length(Source));
  for i := 0 to high(Result) do begin
    Result[i] := Source[i];
  end;
end;

The type has lots and lots of other methods that I have omitted for brevity.

Upvotes: 0

Related Questions