Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is adding SuspendLayout and ResumeLayout reducing performance?

I need to add a lot of controls to a parent control.

But I find if I add ParentControl.SuspendLayout and ParentControl.ResumeLayout before and after I add those controls to the parent, I use stopwatch to measure the ticks: If I remove the code ParentControl.SuspendLayout and ParentControl.ResumeLayout, it will be faster. Why does it happen?

So SuspendLayout and ResumeLayout are not supposed to reduce the time to add sub controls, right? So what's the benefit to use SuspendLayout and ResumeLayout or in other words, if I don't use SuspendLayout and ResumeLayout but add the sub controls directly to parents, what's the bad?

like image 891
spspli Avatar asked Oct 29 '12 13:10

spspli


People also ask

What does SuspendLayout do?

The SuspendLayout and ResumeLayout methods are used in tandem to suppress multiple Layout events while you adjust multiple attributes of the control.

When to use SuspendLayout?

When adding several controls to a parent control, it is recommended that you call the SuspendLayout method before initializing the controls to be added. After adding the controls to the parent control, call the ResumeLayout method. This will increase the performance of applications with many controls.


1 Answers

This is for the usual reason, removing code usually makes your program run faster.

Suspend/ResumeLayout() is pretty universally misunderstood. It will only have an effect when you have controls that have a non-default AutoSize, Dock or Anchor property. It prevents layout accidents when controls have layout properties that affect each other.

If you have a form with hundreds of controls then it is very unlikely that you use these properties at all. Such a massive window does not easily lend itself to automatic layout. So you are calling methods that don't actually do anything, they take time to iterate the layout but for no benefit.

like image 72
Hans Passant Avatar answered Oct 12 '22 11:10

Hans Passant