它是昂贵的创建.NET对象? [英] Is it expensive to create objects in .Net?
问题描述
我刚刚重构同事的code表示,大约,看上去像这样...
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...
}
}
}
现在,这是好多了code设计,是一个Bob大叔的最爱。然而,我的同事认为,它是如此的新,一个对象要贵得多,每次我们要调用此方法。
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.
他是正确的吗?
新解
感谢所有的答复为止。我离开了很多细节,简洁的希望,但他们中的一些已经造成问题的答案。
Thanks for all the responses so far. I left out many details in the hope of brevity, but some of them have caused issues with the answers.
- 工具类不存在。我只是希望把这些方法的类,你都可以看到。实际上这是一个明智的类。
- 有,其实在原来的code 5 AddHistoryEntry方法。所有这一切都拍了很多INT参数。原因之一重构是
AddHistory(0,1,45,3);!
并没有真正告诉你多少 - AddHistoryEntry不从一个紧密的循环调用,但它被广泛整个申请中使用。
- 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.
更正
我现在已经更新了code的例子,因为我犯了一个错误的一些参数。
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.
这篇关于它是昂贵的创建.NET对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!