yoy.be "Why-o-Why"

Do n.GetFirstChild=nil instead of n.Count=0

2021-03-21 17:25  nodecount0  coding delphi  [permalink]

I wish I knew this one sooner! If you've worked with TTreeView before, and know about TTreeNode's HasChildren value, you need to check with OnExpanding, if you need to load the children or not. So I would typically have something like this:

if Node.HasChildren and (Node.Count=0) then //load children nodes

Only now after all these years I happen to come past this in the Vcl.ComCtrls.pas unit:

function TTreeNode.GetCount: Integer;
var
Node: TTreeNode;
begin
Result := 0;
Node := GetFirstChild;
while Node <> nil do
begin
Inc(Result);
Node := Node.GetNextChild(Node);
end;
end;

So I've been throwing away performance all this time! Because my 'are the children loaded yet' check was taking more time if they were and there were a lot of them, expanding nodes was slower. And I never noticed!

So it's a good thing I know this, and now I can just write:

if Node.HasChildren and (Node.GetFirstChild=nil) then //load children

twitter reddit linkedin facebook