Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactoring this code for performance [closed]

Something like this:

Assembly(A):

private void MoveItems(someCollection)
{
   // more code....

   foreach( item x in someCollection)
   {
      int x = getXFoo();
      assemblyB.UpdateOrderView(x)
   }

   //more code....
}

Assembly(B):

private void UpdateOrderView(x)
{
    // more code....

    int y = this.ListCount();

    //......

    FinishDisplay(y)
}

We make a call to MoveItems() which has a collection and for-each loop. So if there are 600 items in the collection we are calling FinishDisplay() method also 600 times. But that's where I need to refactor. I don't need FinishDisplay() to get called each time for each item in the collection. If I can just call it one time at the end, that is enough.

So I am looking for a way to refactor this code so that FinishDiplay() gets called only one time. I have control over the source code so if I need to make some methd public or create some overloads of some methods I can do that too.

like image 250
Bohn Avatar asked Dec 03 '25 17:12

Bohn


1 Answers

You may want to make FinishDisplay public and call it in the consumer instead of UpdateOrderView. If you need a more generic or explicit interface, you could implement a pattern like Windows Form's Control.SuspendLayout and Control.ResumeLayout methods:

private bool autoFinish = true;

public void SuspendAutoFinish() { this.autoFinish = false; }
public void ResumeAutoFinish() { this.autoFinish = true; FinishDisplay(); }

private void UpdateOrderView() {
  // ...
  if(this.autoFinish) FinishDisplay();
}

// consumer
try {
  myImpl.SuspendAutoFinish();
  myImpl.MoveItems(myCollection);
}
finally {
  myImpl.ResumeAutoFinish();
}
like image 61
Matthias Meid Avatar answered Dec 06 '25 08:12

Matthias Meid