【发布时间】:2012-04-16 07:02:18
【问题描述】:
我想知道为什么有两种不同的方式来清除列表视图。一种是致电listview.clear,另一种是listview.items.clear。实际上,这也扩展到许多其他 VCL 组件。必须使用哪种方法,为什么?
【问题讨论】:
标签: delphi
我想知道为什么有两种不同的方式来清除列表视图。一种是致电listview.clear,另一种是listview.items.clear。实际上,这也扩展到许多其他 VCL 组件。必须使用哪种方法,为什么?
【问题讨论】:
标签: delphi
ListView.Clear 只是 ListView.Items.Clear 和 ListItems.BeginUpdate/ListItems.EndUpdate 的包装。看源码:
procedure TCustomListView.Clear;
begin
FListItems.BeginUpdate;
try
FListItems.Clear;
finally
FListItems.EndUpdate;
end;
end;
来自文档:
BeginUpdate 方法暂停屏幕重绘,直到 EndUpdate 方法被调用。使用 BeginUpdate 加速处理并避免 在集合中添加或删除项目时闪烁。
更好的做法是使用BeginUpdate/EndUpdate 来提高速度并避免闪烁。
但是使用ListView.Clear 的主要原因是因为使用“高级VCL 方法”(正如@Arnaud 评论的那样)总是一个好主意,并且实现可能会改变(顺便说一句,该方法是在D7 中引入的)。
编辑:我已经用 10k 个项目(D7/WinXP)测试了TListView:
ListView.Items.Clear:~5500 毫秒ListView.Clear:~330 毫秒结论:不使用BeginUpdate/EndUpdate时,ListView.Clear的速度比ListView.Items.Clear快16倍左右!
【讨论】:
BeginUpdate .. EndUpdate 对clear 有任何帮助。
clear释放每个对象,它会通知VCL每次删除,除非使用BeginUpdate / EndUpdate。这就是两者的区别,也是为什么Clear 比Items.Clear 快得多。直接调用高级 VCL 方法总是一个好主意,而不是进入内部管道,除非您确切知道自己在做什么。
ListView.Clear 是一种在内部调用ListView.Items.Clear 的便捷方法。无论您调用两者中的哪一个,都没有语义差异。
我更喜欢第一个,因为它更短,并且没有显示我目前不感兴趣的内部表示。
【讨论】:
BeginUpdate .. EndUpdate 打电话给另一个,在这种情况下(恕我直言)没有什么不同。
BeginUpdate/EndUpdate 对TListView 造成了巨大的性能问题。