Suggestions on array allocation pattern/rules of thumb?

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

Suggestions on array allocation pattern/rules of thumb?

etrusco
Hello,
In Lazarus I found (pseudo)some code like this:

procedure DoSomething(...)
var
  v_Results: PInteger;
  v_ResultCount: Integer;
begin
  v_Result := nil;
  PrepareData(..., v_Results, v_ResultCount);
  InternalDoSomething(v_Results, v_ResultCount);
end;

procedure PrepareData(..., var p_Results: PInteger; var p_ResultCount: Integer)
begin
  for (...)
    if (...)
    begin
     Inc(p_ResultCount);
     ReallocMem(p_Results, p_ResultCount);
    end;
end;


As you might guess my main gripe is about the repeated calls to
ReallocMem. The real case in the LCL is far from critical, it's
infrequently and the array won't ever be bigger than 10 elements, I
just thought it could a good example to hear from someone
knowledgeable in FPC heap-allocator about any "rules of thumb" :-)
Apart from making the parameters 'out' - ;) - what would you do?
1) This is this ok.
2) Allocate a buffer with maximum size and then trim it after the loop.
3) Declare a type for the maximum size, allocate it on the heap (in
DoSomething).
4) Declare a type for the maximum size, allocate it on the stack (in
DoSomething).
5) Any other options?
Any remarks regarding different scenarios is also appreciated.

Thanks,
Flávio
_______________________________________________
fpc-pascal maillist  -  [hidden email]
http://lists.freepascal.org/mailman/listinfo/fpc-pascal