0

What runs faster?

Setting a default value and changing it-

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

Or-

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

3 Answers 3

6

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

Also, consider:

$foo = $bar ? "" : "someValue"
Sign up to request clarification or add additional context in comments.

2 Comments

I guess he have many if statements.. otherwise yes, there is no motivation to bother about just 1 statement
@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.
1

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

Comments

1

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:

6 Comments

isn't that true for both cases?
No, in the first case he assign the value of $foo before the if statement ;)
Without assign the variable 'default value' before the if statement, using the isset() function will slow (relatively) the execution
I have one word in reply to you, sir. DOH!
oh but wait. he sets foo and then checks bar
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.