A. Fletcher
A. Fletcher

Reputation: 103

Variable Comparison vs Variable Declaration for Code Efficiency in PHP

I have the below code and was wondering which approach is quicker for the PHP compiler. The variable declaration always assigns the value, but loses the check. Whereas the check only has the variable declaration when $checked evaluates as false.

Variable Declaration

$checked = false;
if($checkA == true){
    $checked = true;
}
if($checkB == true){
    $checked = true;
}
if($checkC == true){
    $checked = true;
}

Variable Comparison

$checked = false;
if($checkA == true){
    if(!$checked){
        $checked = true;
    }
}
if($checkB == true){
    if(!$checked){
        $checked = true;
    }
}
if($checkC == true){
    if(!$checked){
        $checked = true;
    }
}

Upvotes: 0

Views: 24

Answers (1)

N69S
N69S

Reputation: 17206

In best cases, they both are the same (3 executions with comparisation exluding jumps). in worse cases, the first one is more performant (6 vs 7 executions)

but best would be

$checked = false;
if($checkA || $checkB || $checkC){
    $checked = true;
}

In all cases, this is a very negligeable performance issue. the gain is so small 1/1000000000 s

Upvotes: 1

Related Questions