tags:

views:

118

answers:

3

What runs faster?

Setting a default value and changing it-

    $foo = "";
    if($bar)
    {
     $foo = "someValue";
    }

Or-

    if($bar)
    {
     $foo = "someValue";
    }
    else
    {
     $foo = "";
    }
+1  A: 

At a guess, the 2nd one "potentially". First one you're potentially setting 2 values. Second one you're definitely only setting one.

Its also a question though of code clarity. If you've got 2 alternatives (e.g turn left or right) then use the "else" statement. If you've got a 'normal' value vs a flag e.g http or https, then use the first one

David Archer
+1  A: 

EDIT: becose you valorize a variable in base to another one, the isset() statement is mandatory.. so the 'faster one' is the second way becose, as David said, yoo valorize the $foo var just one time.

Also consider the Anton suggestion to use the short if syntax (dont know if it speed up the execution)

P.s: if your goal is to speed up many if like that one, use the ' instead of ", becose the content inside "" is being evalutated by php (in case it contain a variable:

DaNieL
isn't that true for both cases?
David Archer
No, in the first case he assign the value of $foo before the if statement ;)
DaNieL
Without assign the variable 'default value' before the if statement, using the isset() function will slow (relatively) the execution
DaNieL
I have one word in reply to you, sir. DOH!
David Archer
oh but wait. he sets foo and then checks bar
David Archer
LOL i've seen it now. is a syntax error or not?
DaNieL
no, not necessarily. $urlString = "http"; if ($isSecure) {$urlString="https";} :-)
David Archer
Agree, just edited
DaNieL
+6  A: 

You absolutely should not be bothered with performance of a single if statement.

Also, consider:

$foo = $bar ? "" : "someValue"
Anton Gogolev
I guess he have many if statements.. otherwise yes, there is no motivation to bother about just 1 statement
DaNieL
@DaNieL If he has a gazillion of `if` statements, that is clearly a code smell. Otherwise, this is not what he should be worried about.
Anton Gogolev