Reputation: 3789
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?
Upvotes: 0
Views: 1547
Reputation: 32632
The cast-iron rule for profilers is that absolute results aren't accurate or important. They are only useful as a comparison tool - i.e. 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 - i.e. an operator overload on the value class.
Upvotes: 2
Reputation: 3255
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.
Upvotes: 2