Search code examples
flutterperformancedartoptimization

If case null vs if null


Is there any difference in terms of performance between

if (variable == null) ...

and

if (variable case null) ...

How compiler handles this? Does case work more like const?

Also, what about case vs is?


Solution

  • if (variable == null) should be identical to if (variable case null). Why would you expect the compiler to treat them differently? I would expect that it would be fairly trivial for the compiler to treat them the same way unless there's evidence to the contrary.

    If you're in doubt, you can use godbolt.org to compare the compiled output. Given:

    int? f() => null;
    
    void main() {
      var x = f();
      if (x == null) {
        print("null");
      }
    }
    

    versus

    int? f() => null;
    
    void main() {
      var x = f();
      if (x case null) {
        print("null");
      }
    }
    

    I get the same disassembly from both.