Вопрос

In both Java and .Net, I've heard that using null first if (null == myObject) is more performant than using the object first if (myObject == null). While I think this is probably true, I'm not certain and would like to know from SO users. Personally, I think it reads better if the object is referenced first, but if there's any performance gain by using null first, I'll opt for that instead.

Это было полезно?

Решение

They're exactly the same. If there was a difference, any compiler would make the swap as there is absolutely no functional difference.

Другие советы

Surprise, they compile differently in Java:

if (myObject == null);
if (null == myObject);

compiles to

 8 aload_1
 9 ifnonnull 12 (+3)
12 aconst_null
13 aload_1
14 if_acmpne 17 (+3)

(This was compiled using javac 1.6.0_24.)

Putting the object reference first results in two instructions, and putting the null first results in three instructions. On that basis, if (myObject == null) might be faster.

However, as Thorbjørn Ravn Andersen points out, when using a JIT compiler the number of bytecode instructions doesn't mean much, as the bytecode will be converted to native code before execution anyway. And even if there is a performance difference, I doubt it would be measurable.

I would expect Java to generate exactly the same bytecode for both versions (probably the ifnull bytecode), so use whichever reads better to you.

Can't say for Java but I will be very surprised if there, it is different.
In a C# sample I write

void Main()
{
    object o = new object();

    if(null == o)
        Console.WriteLine("o is null");

    // to force a reload of the registers
    o = new object();

    if(o == null)
        Console.WriteLine("o is null");
}

the resulting IL code is

IL_0000:  newobj      System.Object..ctor
IL_0005:  stloc.0     // o
IL_0006:  ldloc.0     // o
IL_0007:  brtrue.s    IL_0013
IL_0009:  ldstr       "o is null"
IL_000E:  call        System.Console.WriteLine
IL_0013:  newobj      System.Object..ctor
IL_0018:  stloc.0     // o
IL_0019:  ldloc.0     // o
IL_001A:  brtrue.s    IL_0026
IL_001C:  ldstr       "o is null"
IL_0021:  call        System.Console.WriteLine

NO DIFFERENCE AT ALL

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top