Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it expensive to create objects?

I have just refactored a colleague's code that, roughly, looked like this...

public class Utility
  public void AddHistoryEntry(int userID, HistoryType Historytype, int companyID)
  {
    // Do something...
  }
  public void AddHistoryEntry(int userID, HistoryType historyType, int companyID, string notes)
  {
    // Do something...
  }
}

To this...

public class HistoryEntry
{
  public long UserID { get; private set; }
  public HistoryType HistoryType { get; private set; }
  public long CompanyID { get; set; }
  public string Notes { get; set; }

  public HistoryEntry(long userID, HistoryType historyType)
  {
    this.UserID = userID;
    this.HistoryType = historyType;
  }
}

public class Utility
{
  public void AddHistoryEntry(HistoryEntry entry)
  {
    // Do something...
  }
}

Now, this is much better code design and is an Uncle Bob favourite. However, my colleague argues that it is so much more expensive to new-up an object every time we want to call this method.

Is he correct?

Further Explanation

  • Utility class doesn't exist. I just wanted to put the methods in a class for you all to see. In actuality it's in a sensible class.

  • There were, in fact, 5 AddHistoryEntry methods in the original code. All of which took a lot of int parameters. One reason for the refactoring was that AddHistory(0, 1, 45, 3); doesn't really tell you much!

  • AddHistoryEntry is not called from a tight loop, but it is widely used throughout the application.

Corrections

I've now updated the code examples as I had made a mistake with some of the parameters.

like image 311
Chris Arnold Avatar asked Jan 20 '10 21:01

Chris Arnold


1 Answers

He might be correct if you have millions of these objects in memory simultaneously. But if you don't, then he's bringing up what is almost certainly a moot point. Always choose a better design first, and then modify it only if you're not meeting performance requirements.

like image 81
Kaleb Brasee Avatar answered Jan 02 '23 22:01

Kaleb Brasee