15
Question mainly in PHP, in the Wordpress documentation exists an excerpt which explicitly speaks that it is interesting to use the famous Yoda conditions, although it does not give a good and real reason.
When making logical comparisons involving variables, always put the variable on the right side and put constants, literals or calls function on left side. (Free Translation)
Specifically me, always found ugly and read not easy this kind of coding: if(10 == $teste){ // do anything }
or if("string" == $teste){ // do anything }
This doubt arose me after a colleague of mine recommend me to install a plugin in Brackets called Brackets php code quality tools that theoretically points out errors in coding... and in lines of the type if($teste == 10){ // do anything }
he generates warnings, he recommends the use of the blessed Yoda conditions.
The first time I saw this type of coding came into my mind to be to facilitate the processing, like first the processor just picks up the constant and then accesses the location of the variable in memory, but stopping to think I see no difference!
I did tests in PHP and Javascript and saw no difference in performance with the naked eye...
Follows tests:
PHP
echo "Normal<br/>";
$a = "a";
for($x = 0; $x <= 5; $x++){
$time_start = microtime(true);
if($a == "a"){
//
}
$execution_time = microtime(true) - $time_start;
echo $execution_time.'s<br/>';
}
echo "-------------<br/>";
echo "Yoda Condition<br/>";
$a = "a";
for($x = 0; $x <= 5; $x++){
$time_start = microtime(true);
if("a" == $a){
//
}
$execution_time = microtime(true) - $time_start;
echo $execution_time.'s<br/>';
}
Javascript
Is there a good reason to use Yoda Conditions in some programming language? Or is it just the customer’s taste? Is there any difference in performance (in some language)?
Using Yoda condition the elaborate question was. Good padawan you are.
– ShutUpMagda