Friday, November 28, 2008

PHP Loop Benchmarking - WHILE vs FOR

I was very bored today, when I suddenly realised that I should do some benchmarking for PHP myself. I created a script (can be found at thephpcode pastebin: http://thephpcode.pastebin.com/f80e53fe) and run it on my xampp localhost.

In the php benchmarking script, i am comparing 3 loops: FOR, WHILE and FOREACH. Amazingly, but not surprising, WHILE loop is the fastest compared to FOR and FOREACH, and as expected FOREACH is the slowest.

This is my output:
0.000854015350342 seconds
// for the FOR loop with 10000 times
0.000696897506714 seconds
// for the WHILE loop with 10000 times
10000 elements
// the number of elements in the array
0.00111794471741 seconds
// for the FOREACH loop with 10000 times


I read about the WHILE loop on Javascript that WHILE is faster than FOR, but I didn't know that the same thing applies in PHP too. Well, here's a learning point for all of us.

Note that the timings taken are an average of 5 runs spreaded across 5 mins (i.e. 1 run per minute) for the most accurate timings. Please note that the timings may differ from computer to computer. I am using Intel QuadCore 2.4GHz, 4GB RAM, Windows XP SP3, XAMPP 1.7.1, PHP 5.2.9.

Sunday, November 23, 2008

Multiple Pages with one PHP file

OMG.. i am so sorry for the delay. i was seriously slow and lazy as promised. well, today i am going to talk about having multiple pages with only one php files.

many PHP noobs, they create one small module with tons and tons of pages. that's really bad because you duplicate loads and loads of the same thing! This is made possible using the system-defined variable $_GET, which returns all $_GET variable .. eg index.php?a=b to get the value 'b' you can use $_GET['a'].

what you can do is to combine these pages into one php files. this makes things easy as you are able to backup less files: instead of hundreds of files.

Previously you can have:
+ index.php
+ postback.php
+ about.php
+ process.php

now you can have:
+ index.php
+ index.php?p=pb
+ index.php?p=a
+ index.php?p=prc

Simply in index.php you just have to use IF ELSE statements, or use any other conditional statements.

index.php:
<?php

if($_GET['p']=='pb'){
// display page for postback
}elseif($_GET['p']=='a'){
// for about page
}elseif($_GET['p']=='prc'){
// for processing
}else{
// displaying main page...
}

?>


This is simple and easy. If you have common template for all the pages, you can combine and put them before or after the IF conditions. Most client browsers identify different GET headers as different pages, so it doesn't affect much of your application.