9

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)

7
  • I think you can suspend rendering/relayouting, which might speed up this code. Commented Nov 19, 2012 at 14:16
  • In situations like these, your best friend is a decompiler like Reflector.
    – leppie
    Commented Nov 19, 2012 at 14:16
  • @leppie I'd rather benchmark it first. Commented Nov 19, 2012 at 14:17
  • 1
    I would use a profiler to determine the best course of action. Commented Nov 19, 2012 at 14:17
  • this is one of those times I'd say: You already have two options. Why don't you just try it both ways? Find out what works better in your case?
    – hometoast
    Commented Nov 19, 2012 at 14:19

1 Answer 1

5

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.

1
  • 3
    Why ResumeLayout(false)+PerformLayout() instead of ResumeLayout()? Commented Nov 19, 2012 at 14:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.