简体   繁体   English

检查对象是否为空-性能差异

[英]Check if object is null - performance differences

I just discovered a weird behaviour in my application while doing a perfomance analysis with ANTS Performance Profiler: 在使用ANTS Performance Profiler进行性能分析时,我刚刚在应用程序中发现了一个奇怪的行为:

public void set_SelectedObject(object value)
{
    if (value == null) //65ms
    {
       //do anything
    }
}

This check takes 65ms whereas other checks if objects are null take less than 0,Xms. 此检查需要65毫秒,而其他检查对象是否为null的检查则小于0,Xms。 What could be the reason for this? 这可能是什么原因? I thought a null-check is always constant no matter what value is passed - Does it depend on the size of my object? 我认为无论传递什么值,空检查始终是常数-它是否取决于对象的大小?

It's nonsense. 废话 Checking the value against null will always have similar impact on your performance. 将值检查为null总是会对您的性能产​​生类似的影响。 It may take 65 ms, because a reference you're sending to the method may actually be a null, which triggers the logic inside your if statement or the oposite - there's some heavy logic that's being fired, when the object is not a null. 这可能需要65毫秒,因为您要发送给该方法的引用实际上可能为null,这会触发if语句或相反对象内的逻辑-当对象不是null时,会触发大量逻辑。

The only theoretical reason I could imagine is that you use an overloaded == operator for some class, but it'd have to be really poor piece of code if it wouldn't check for null first. 我可以想象的唯一理论上的原因是,您对某些类使用了重载的==运算符,但是如果它不首先检查null的话,那将是一段很糟糕的代码。

The cast-iron rule for profilers is that absolute results aren't accurate or important. 探查器的铸铁法则是绝对结果不准确或不重要。 They are only useful as a comparison tool - ie is my code faster with or without change X? 它们仅用作比较工具-即在更改X或不更改X的情况下,我的代码是否更快? That said, 65ms is still a substantial chunk of time that shouldn't appear as a result of profiler variance, unless the profiler is really bad. 就是说,65ms仍然是相当大部分的时间,除非分析器确实很差,否则不应因分析器差异而出现。

I haven't used the C# ANTS profiler, I would be amazed if it gave you a timing for single line of code like that. 我没有使用过C#ANTS探查器,如果它为您提供了像这样的单行代码的计时,我会感到惊讶。 Are you sure it's not the time to execute the entire block surrounded by the if-statement? 您确定不是时候执行由if语句包围的整个块了吗?

If it is giving you a time for just that line, that implies a function call is being made - ie an operator overload on the value class. 如果它只是给您一点时间,那意味着正在进行函数调用-即值类上的运算符重载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM