j2emanue j2emanue - 2 years ago 133
Java Question

java - fastest way to check if object is null

Someone told me its faster to do this

if(null == object)


vs doing this

if(object == null)


I think theres no difference. Please confirm the efficiency/performance is the same.

Note... my friend did a performance test already to prove that the first is slightly faster.

update on why some do it this way:
say you accidentally do an assignment with " = " instead of the intended equality check such as "==", the first will give a compiler error if you use null first. so gramatically it is better.

Answer Source

I wrote a program to test this. All it does it call two methods repeatedly. The only contents of the methods are the two comparisons we want to test the performance of.

public class StackOverflow {
    public static void main(String[] args) {
        String s = "";
        while (true) {
            a(s);
            b(s);
        }
    }
    private static void a(String s) {
        if (s == null);
    }
    private static void b(String s) {
        if (null == s);
    }
}

I attached a profiler to my program. Here are the results after 70 seconds of execution:

enter image description here

As you can see, the CPU time is nearly four times lighter in a(). This suggests that the comparison s == null is indeed faster than null == s.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download