我有2个或更多的动态字符串数组填充一些巨大的数据,我想将这个2数组合并到一个数组,我知道我可以用一个for循环这样做:
var Arr1,Arr2,MergedArr: Array of string; I: Integer; begin // Arr1:= 5000000 records // Arr2:= 5000000 records // Fill MergedArr by Arr1 MergedArr:= Arr1; // Set length of MergedArr to length of ( Arra1 + Arr2 )+ 2 SetLength(MergedArr,High(Arr1)+ High(Arr2)+2); // Add Arr2 to MergedArr for I := Low(Arr2)+1 to High(Arr2)+1 do MergedArr[High(Arr1)+ i]:= Arr2[i-1]; end;
但是在巨大的数据上是缓慢的,是否有更快的方式像复制数组内存数据?
解决方法
您可以使用内置的Move功能将内存块移动到另一个位置.参数是源和目标内存块和要移动的数据的大小.
由于您正在复制字符串,源数组在合并后必须通过将其填充为零来销毁.否则,对于字符串的引用将会在程序中造成破坏和破坏.
var Arr1,MergedArr: Array of string; I: Integer; begin SetLength(Arr1,5000000); for I := Low(Arr1) to High(Arr1) do Arr1[I] := IntToStr(I); SetLength(Arr2,5000000); for I := Low(Arr2) to High(Arr2) do Arr2[I] := IntToStr(I); // Set length of MergedArr to length of ( Arra1 + Arr2 )+ 2 SetLength(MergedArr,High(Arr1)+ High(Arr2)+2); // Add Arr1 to MergedArr Move(Arr1[Low(Arr1)],MergedArr[Low(MergedArr)],Length(Arr1)*SizeOf(Arr1[0])); // Add Arr2 to MergedArr Move(Arr2[Low(Arr2)],MergedArr[High(Arr1)+1],Length(Arr2)*SizeOf(Arr2[0])); // Cleanup Arr1 and Arr2 without touching string refcount. FillChar(Arr1[Low(Arr1)],Length(Arr1)*SizeOf(Arr1[0]),0); FillChar(Arr2[Low(Arr2)],Length(Arr2)*SizeOf(Arr2[0]),0); // Test for I := Low(Arr1) to High(Arr1) do begin Assert(MergedArr[I] = IntToStr(I)); Assert(MergedArr[I] = MergedArr[Length(Arr1) + I]); end; // Clear the array to see if something is wrong with refcounts for I := Low(MergedArr) to High(MergedArr) do MergedArr[I] := ''; end;