创建对象是否昂贵? [英] 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...
}
}
为此...
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.
他正确吗?
进一步的说明
-
实用程序类不存在。我只是想将这些方法放在一个类中,以供大家查看。实际上,它属于明智的选择。
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.
实际上,原始代码中有5个AddHistoryEntry方法。所有这些都使用了很多int参数。重构的原因之一是 AddHistory(0,1,45,3);
并不能告诉您很多信息!
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不是从紧密循环中调用的,而是在整个应用程序中广泛使用的。
AddHistoryEntry is not called from a tight loop, but it is widely used throughout the application.
更正
我现在更新了代码示例,因为我对某些参数弄错了。
I've now updated the code examples as I had made a mistake with some of the parameters.
推荐答案
如果您同时在内存中有数百万个这些对象,则可能是正确的。但是,如果您不这样做,那么他将提出几乎可以肯定的争论点。始终先选择一个更好的设计,然后仅在不满足性能要求的情况下进行修改。
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.
这篇关于创建对象是否昂贵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!