简体   繁体   中英

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:

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. 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. 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.

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.

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? 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.

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. Are you sure it's not the time to execute the entire block surrounded by the if-statement?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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