What should be the best practice to check the object ?

Hi,
Normally we check a value by this format

if ( obj == null )
{
//do some code
}
I know it is good for readability.

But for performance reason I am suggested by one of my coleagues that

we shuold check the constant value first i.e.

if ( null == obj )
{
//do some code
}

What is the best possible way to check the object
Could any body give the proper reason to use the later one.



Answer this question

What should be the best practice to check the object ?

  • Henk vd Geld

    What do you mean clear you



  • Rob S

    It is not really for performance but to catch bugs like

    Boolean bSomething = false;
    if (bSomething = true)
    {
       ...this code will execute
    }

    at compile time instead of maybe when debugging. It is a recommendation to always write constants on the left side of == when comparing with equality operator. The performance increase is in less possible bugs to debug!

    if (true = bSomething) // will not even compile

    EDIT: To be clear, it is to catch types where you type = instead of ==



  • ZeeGee

    your coleagues seem to be wrong :)

    here the result of my little test :)

    Left u have (obj == null)

    right u have (null == obj)

    There are the time results for 1.000.000.000 checks


    Object not null
    0: 00:00:06.6562500 - 00:00:06.8125000
    1: 00:00:06.7343750 - 00:00:06.8281250
    2: 00:00:06.7500000 - 00:00:06.5312500
    3: 00:00:06.6093750 - 00:00:06.5937500
    4: 00:00:06.9687500 - 00:00:06.6250000
    5: 00:00:06.5781250 - 00:00:06.8750000
    6: 00:00:06.6250000 - 00:00:06.7968750
    7: 00:00:06.7343750 - 00:00:06.5156250
    8: 00:00:06.5468750 - 00:00:06.5156250
    9: 00:00:06.9218750 - 00:00:06.6093750

    Object is null
    0: 00:00:07.0468750 - 00:00:07.3593750
    1: 00:00:07.1250000 - 00:00:07.4531250
    2: 00:00:07.0000000 - 00:00:06.9843750
    3: 00:00:07.0156250 - 00:00:07.1093750
    4: 00:00:07.2656250 - 00:00:07.0312500
    5: 00:00:07.2500000 - 00:00:07.2031250
    6: 00:00:07.2812500 - 00:00:07.1718750
    7: 00:00:06.9843750 - 00:00:07.0000000
    8: 00:00:07.0000000 - 00:00:07.4687500
    9: 00:00:07.0625000 - 00:00:07.0781250


  • Martin R

    Not sure if ther is any difference ...

    only 1 way to know ... just run a test :)


  • Rod A.

    OK

    Thanks



  • What should be the best practice to check the object ?