Performance of changing the position of hundreds of WinForms controls

.net, performance, winforms

Solution

You can optimize it like follows to avoid continuous repainting:

panel1.SuspendLayout();

for (int i = 0; i < panel1->Controls->Count; ++i) {
{
    // do reposition
}   

panel1.ResumeLayout(false);
panel1.PerformLayout();

or

panel1.ResumeLayout()

@CodesInChaos: Good point! It looks to be the same, but it isn't. To use

- ResumeLayout(false)/PerformLayout() or

- ResumeLayout()

will influence how the result looks like as explained here.

Problem

I have a loop: ``` for (int i = 0; i < panel1->Controls->Count; ++i) { Control^ ctl = panel1->Controls[i]; ctl->Location.Y = i*10; } ``` Is it okay if I have 200 or 300 controls in panel1? Or it will be better if I add this: ``` if (ctl->Location.Y != i*10) ctl->Location.Y = i*10; ``` I just don't know if .NET's controls will repaint anyway (it will take time) or they will automatically check if there is no need to repaint (still same location)

Original source