resharper-unity icon indicating copy to clipboard operation
resharper-unity copied to clipboard

"Comparison to null is expensive" warning can be misleading

Open cathei opened this issue 3 years ago • 3 comments

The warning, Avoid null comparisons against UnityEngine.Object subclasses shows for this code:

if (obj != null) DoSomething();

But not showing for this code:

if (obj) DoSomething();

Since bool cast operator of UnityEngine.Object does the same thing as comparing to null, the warning should be shown as same. Otherwise, it can mislead users to use bool cast instead, which is worse practice as it is less explicit.

cathei avatar Oct 18 '22 00:10 cathei

Yeah, they both use the same CompareBaseObjects() inside, no difference in performance. The warning is misleading for sure.

That's what is inside of them:

    public static bool operator ==(Object x, Object y) => Object.CompareBaseObjects(x, y);
    public static bool operator !=(Object x, Object y) => !Object.CompareBaseObjects(x, y);
    public static implicit operator bool(Object exists)
    {
      return !Object.CompareBaseObjects(exists, (Object) null);
    }

    private static bool CompareBaseObjects(Object lhs, Object rhs)
    {
      bool flag1 = (object) lhs == null;
      bool flag2 = (object) rhs == null;
      if (flag2 & flag1)
        return true;
      if (flag2)
        return !Object.IsNativeObjectAlive(lhs);
      return flag1 ? !Object.IsNativeObjectAlive(rhs) : lhs.m_InstanceID == rhs.m_InstanceID;
    }

NikolayTimofeev avatar May 21 '24 10:05 NikolayTimofeev

Do you mean the plain underline highlight for performance related info inside Update and related methods?

citizenmatt avatar May 22 '24 07:05 citizenmatt

Yes

NikolayTimofeev avatar May 24 '24 15:05 NikolayTimofeev