I hope somebody can give me some feedback on an idea how to simplify some of my code:

I hope somebody can give me some feedback on an idea how to simplify some of my code:
I have a lot of global arrays (Tarray<>) and a lot of For loops to read and fill data. When filling data I check for Length of array if it needs resizing:

SetLength(Array, 100);
vIdx := 0;
for i := 0 to n do
begin
// Check array size
if vIdx > High(Array) then
SetLength(Array, Length(Array * 2);
...
Array[vIdx] := ...
Inc(vIdx);
end;


Sometimes when I have multiple for loops on the same array in 1 method, I simplified by creating a local method CheckArray that checks for length and resizes if needed:

// local method
procedure CheckArray(aArrat: Tarray<>; aIdx: integer);
...

And I just call CheckArray(...) in For loop. The code is much neater.

And now I'm thinking of just creating CheckArray() for all types of arrays I have, with overload, so I can call CheckArray() with any array type from any For or other loops.

So, this would look like:

procedure CheckArray(aArray: Tarray; aIdx: integer); overload;
procedure CheckArray(aArray: Tarray; aIdx: integer); overload;
procedure CheckArray(aArray: Tarray; aIdx: integer); overload;
...

Before I go and start changing all my for loops, I am trying to see if this makes sense or not. If anybody tried that and for some reason was not working well.

Thanks!

Comments

  1. Lars Fosdal Would you share a bit of your custom TArray class?
    My question here of course shows my not-so-perfect design with 100s of arrays, but I managed to optimize a lot of things and looking up data in my arrays is fast enough, with the way I implemented my indexes.

    ReplyDelete
  2. Mike Torrettinni - Sorry for my late reply. I read this on my mobile at the time, and forgot to follow up. I can't really share the whole thing, as it was developed for my employer, and contains some code which is specific to us. I've been mulling the thought of releasing a clean version of it, but currently I don't have the time to do so. It is geared towards being a back end for grids, charts, etc. It is basically an array of column arrays, and contains a lot of presentation oriented code (formatting, layout, etc) which will be confusing without proper examples. The data set unit is 3200 lines long - and the grid view unit is another 2000 lines and it's currently tied to TMS TAdvStringGrid.

    If you give me an example of the kind of data you put in your arrays, and their typical life time operations - I could try to make a generic example instead?

    ReplyDelete
  3. Thank you, I appreciate you coming back with this. I was more curious than in need of something like this, so please don't waste time - but if you ever prepare something on github, please do share. At the time I was just in the middle of creating my first TArray generic method and eventually I made it work! :)

    ReplyDelete

Post a Comment