skip to Main Content

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?

2

Answers


  1. The performance difference between these two methods is almost non-existent. You should use the one that makes your code more readable.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search