对于我的生活,我无法弄清楚我的代码中的这种性能影响。我有一个容器对象,我在其中测量运行构造函数(下面的对象)需要多长时间,公共(public)构造函数中的计时代码
public class WorkUnit : IWorkUnit
{
private JobInformation m_JobInfo;
private MetaInfo m_MetaInfo;
private IPreProcJobInfo m_PreprocDetails;
readonly private Guid m_ID;
private Guid m_ParentID;
private Guid m_MasterJobID;
private string m_ErrorLog = string.Empty;
private PriorityKeeper m_Priority;
private WorkUnitClassification m_Classification;
private IJobPayload m_CachedPayload;
private IJobLogger m_Logger;
private EventHandler<JobEventArgs> m_IsFinished;
private ReaderWriterLockSlim m_Lock;
public WorkUnit(string InputXML, Guid JobID, IJobLogger Logger)
{
DateTime overstarttime = DateTime.Now;
try
{
....Do Stuff....
}
catch(XMLException e)
{...}
catch(Exception e)
{
...
throw;
}
double time = (DateTime.Now - overstarttime).TotalMilliseconds
Console.WriteLine("{0}", time);
}
/// <summary>
/// Private Constructor used to create children
/// </summary>
private WorkUnit(Guid MasterID, Guid ParentID, WorkUnitClassification Classification, PriorityKeeper Keeper)
{...}
[OnDeserializing()]
private void OnDeserialize(StreamingContext s)
{...}
public PriorityKeeper PriorityKey
{...}
public bool HasError
{...}
public bool Processing
{...}
public bool Splittable
{...}
public IEnumerable<IWorkUnit> Split(int RequestedPieces, int Bonds)
{...}
public void Merge(IResponse finishedjob)
{...}
public ReadOnlyCollection<IWorkUnit> Children
{...}
public bool IsMasterJob
{...}
public Guid MasterJobID
{...}
public Guid ID
{...}
public Guid ParentID
{...}
public EnumPriority Priority
{...}
public void ChangePriority(EnumPriority priority)
{...}
public string ErrorLog
{...}
public IMetaInfo MetaData
{...}
public IJobPayload GetProcessingInfo()
{... }
public IResponseGenerator GetResponseGenerator()
{... }
}
现在,我正在测量创建对象所需的总时间
DateTime starttime = DateTime.Now;
var test = new WorkUnit(temp, JobID, m_JobLogger);
double finished = (DateTime.Now - starttime).TotalMilliseconds;
而且我一直得到以下性能数据 -
构造函数时间 - 47 毫秒
对象创建时间 - 387 毫秒
47 ms 还可以,387 真的很差。取出日志可以忽略不计地改变这些数字。有谁知道为什么要花这么长时间?我的系统是 VS 2008 SP1,目标是 Windows XP 上的 .NET 3.5 SP1。我将不胜感激任何解释。我很快就会打破探查器,但我觉得它无法深入到我需要解释这种行为的水平。感谢您的帮助。
编辑:我正在发布中运行
最佳答案
您确定您看到的是对象创建时间而不是 CLR 启动的效果吗?
尝试在循环中运行测试 50 次并忽略第一个结果。
关于C# 对象创建比构造函数调用慢得多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1717051/