Friday, August 19, 2005

if-else

While some programmers emphasize writing codes which have more readability, I prefer writing codes which are much much more efficient. Why? Because it makes your program run faster and 'smoother' and it also shows your quality as a programmer.

If you have done programming work before, I am sure you have used the if-else statement. However, I really think that if-else statement is sometimes inefficient. For some simple cases (like the one I am about to demonstrate below), if-else statement are found to be less efficient.

A very simple example of if-else statement:

my $x=0;
my $string='';

if ($x > 10) {
$string='bigger than ten';
} else {
$string='lesser than or equal to ten';
}

Note: this code is used just for demonstration purpose only. It's almost impossible that you will need exactly the same code in your program :)

The simple task above can also be done in one simple line by using the ?: operator.

my $x=0;
my $string='';

$string=($x > 10)? 'bigger than ten' : 'lesser than or equal to ten';

I used the Benchmark module to compare code efficiency for each method. In my computer, the ?: operator is 13% faster than the if-else method. Not only does it shorten your program runtime, but also shortens your time typing your program code. :)

Below is my favorite, by using 'and' and 'or'. Unfortunately I seldom see it being used. However, I use it quite often in my programs.

my $x=0;
my $string='';

($x > 10 and $string='bigger than ten') or $string='lesser than or equal to ten';

At first, it may seem strange and unusual, but wait until you get used to it, you will love it! :) By using the benchmark module, in my computer I found this 'and/or' method to be 29% faster than the if-else method.

As you can see, the 'and/or' method is the fastest to do the simple task. However, if you don't like it or find it less readable, I still recommend the ?: operator. Avoid using if-else statement for such an easy and simple task. The ?: operator is better and the 'and/or' method is the best in my opinion. :)