Wednesday, August 5, 2009

Improving and Speed up Conditional Expressions

This is something cool and you can implement in your PHP scripts, and also you should make this a habit for most of your programming languages - and that is Short Circuit Evaluation.

Consider the following code:

<?php

function a(){
echo 'a';
return true;
}

function b(){
echo 'b';
return false;
}

if(b() && a()){
echo 'c';
}

?>


When run, the output is only 'b'. Reason being that when the if statement is run, the checks from bracket then left to right. If the first expression evaluates into false, the second will not be run.

Now take a look at the OR comparison operator.

<?php

function a(){
echo 'a';
return false;
}

function b(){
echo 'b';
return true;
}

if(b() || a()){
echo 'c';
}

?>


This time, the output is 'bc'. Reason being that the expression in IF will be evaluated to the first true. if the first true is found, the rest will not be executed.

This allows you to speed up your application. Think about the following code:

<?php

$url = htmlentities($_POST['url']);

if($url == '' || validate::url($url)){
echo 'URL is not valid.';
}else{
echo 'Valid URL provided';
}

?>


It'll help to save time if the string is empty - since Short Circuit Evaluation parses that $url is empty, so it's a true and it won't bother to execute the rest of the expression.

No comments: