Why is adding SuspendLayout and ResumeLayout reducing performance?

spspli picture spspli · Oct 29, 2012 · Viewed 16.1k times · Source

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?

Answer

toong picture toong · Aug 23, 2013

You probably want to use .ResumeLayout(false) instead. Calling mySubPanel.ResumeLayout() equals to .ResumeLayout(true), which means it should re-layout this control (and everything child-control that is not suspended at that point) immediately.

MSDN quote: "Calling the ResumeLayout method [without parameters] forces an immediate layout if there are any pending layout requests." [1]

If you are like adding 100 controls to a panel, you want to use an approach like this:

  1. mainPanel.SuspendLayout()
  2. create child control
  3. call child.SuspendLayout()
  4. change the child control properties
  5. add the child control to the mainPanel
  6. call child.ResumeLayout(false) - this means: next layout run, relayout this control, but not immediately
  7. repeat (2-6) for every child-control
  8. call mainPanel.ResumeLayout(true) - this means: relayout my mainPanel and every child-control now!

Note: without SuspendLayout(), every property change for a control would invoke the layout-routine -- even changing the .BackColor makes your control re-layout itself.

[1] http://msdn.microsoft.com/en-us/library/y53zat12.aspx