Question

I always look into how to optimize the code more and more every day, and how I can learn to code faster code.

Looking at some minified JS online I notice the change of a few IF into a statement and I thought that it might be a very good idea to start using it in PHP as well.

<?php
if(!isset($myVar) || $myVar == 'val'){
    $myVar = 'oldVal';
}
if(isset($myVar2) && $myVar2 == 'oldVal'){
    $myVar2 = 'newVal';
}
?>

into

<?php
(!isset($myVar) || $myVar == 'val') && $myVar = 'oldVal';
isset($myVar2) && $myVar2 == 'oldVal' && $myVar2 = 'newVal';
?>

As I like the new syntax, I started to use it more and more thinking to save processing time, but do I really save any or there is no difference internally between the two ?

(The example code is just an EXAMPLE, to only show the technique)

Était-ce utile?

La solution

I used this code to profile both approaches:

<?php

$iterations = 1000000;
$startTime = microtime( true );

$i = 0;
while( ++$i < $iterations ) {
    if(!isset($myVar) || $myVar == 'val'){
        $myVar = 'oldVal';
    }
    if(isset($myVar) && $myVar == 'oldVal'){
        $myVar = 'newVal';
    }
}

echo 'First Running Time: ' . (microtime(true) - $startTime) . "\n";


$startTime = microtime( true );
$i = 0;
while( ++$i < $iterations ) {
    (!isset($myVar) || $myVar == 'val') && $myVar = 'oldVal';
    isset($myVar) && $myVar == 'oldVal' && $myVar = 'newVal';
}

echo 'Second Running Time: ' . (microtime(true) - $startTime) . "\n";

The results:

(1st Run)

First Running Time: 0.38401508331299

Second Running Time: 0.40315389633179

(2nd Run)

First Running Time: 0.38593697547913

Second Running Time: 0.40187788009644

Conclusion: Your method is slower, but the amount is so small that even if it weren't you would still be better off writing more readable code.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top