Mega Code Archive

 
Categories / Delphi / Algorithm Math
 

Something about large arrays

Title: Something about large arrays Question: Working with large arrays? Answer: Using large arrays is not a problem with Delphi. But there is a thing you must keep in mind. See the two procedures below (note that we use const parameter to force the compiler to use pointer and not to copy the whole array in the stack): type LargeArray = array[1..100, 1..1000000] of Integer; procedure SetToZero(const AnArray: LargeArray); var A, B: Integer; begin for A := 1 to 100 do for B := 1 to 1000000 do AnArray[A, B] := 0; end; procedure SetToZero2(const AnArray: LargeArray); var A, B: Integer; begin for B := 1 to 1000000 do for A := 1 to 100 do AnArray[A, B] := 0; end; The first procedure goes through the array cylcling first the right dimension and then the left. SetToZero2 first cycles the right then the left dimension. Do the procedures work equally? If we were using a small array the answer would be yes. But this array is using 400MB RAM (100 * 1000000 * SizeOf(Integer)). It is obvious that most part of it will be put in the swap file. Every array is situated continously in the memory begining with the rightmost dimension. For example AnArray[m, n] will be situated like this: AnArray[1, 1] ...... AnArray[1, n], AnArray[2, 1] ...... AnArray[2, n], AnArray[3, 1] ...... AnArray[1, n] ...... AnArray[m, 1] ...... AnArray[m, n] So in the first procedure we are accessing the memory continously, but in SetToZero2 we are jumping 1MB ahead to get the next element and then go back 1MB. This way we are confusing the OS - it can't predict what we are going to read and this results in slowing the process noticably. So it is important to try using the arrays this way whenever it is possible. P.S. This procedures are just for demonstration purpose. If you want to initialize an array it is better to use FillChar(AnArray, SizeOf(AnArray), 0);