Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Changing context

Status
Not open for further replies.

rrsub

MIS
Oct 23, 2002
536
US
I'm a big fan of clean code and I use HEREDOCS plenty. I always see code from others where the context is changed from HTML to PHP and vice versa multiple times in the script.

Maybe I'm testing this wrong but I decided to time 3 simple scripts and changing context is the fastest by my results.

Script 1 - Averages .256 of a second
Code:
<?PHP
for($i=1;$i<=100;$i++)
{
	for($j=1;$j<=100;$j++)	
	{
		?>Block <?PHP print $i;?> Number <?PHP print $j;?><br> <?PHP
	}
}
?>

Script 2 - Averages .358 of a second
Code:
<?PHP
for($i=1;$i<=100;$i++)
{
	for($j=1;$j<=100;$j++)	
	{
		print"Block $i Number $j<br>";
	}
}
?>

Script 3 - Averages .528 of a second
Code:
<?PHP
for($i=1;$i<=100;$i++)
{
	for($j=1;$j<=100;$j++)	
	{
		print <<<EOF
		
		Block $i Number $j<br>

EOF;
	}
}
?>

Am I doing something wrong or is changing context the performance way to go?

 
I changed the script a little so that the script itself is logging its runtime using microtime(). As an example, here is your first script:

Code:
<?php
$begin = microtime(TRUE);
for ($i=1;$i<=100;$i++)
{
        for ($j=1;$j<=100;$j++)
        {
                ?>Block <?PHP print $i;?> Number <?php print $j;?><br><?php
        }
}
$end = microtime(TRUE);
error_log($end - $begin ."\n", 3, 'test1.log');
?>

I also created CGI versions of the scripts (running PHP as the command interpreter). An example version of your first script is:

Code:
#! /usr/local/bin/php
<?php
print "Content-type: text/html\r\n\r\n";
$begin = microtime(TRUE);
for ($i=1;$i<=100;$i++)
{
        for ($j=1;$j<=100;$j++)
        {
                ?>Block <?PHP print $i;?> Number <?php print $j;?><br><?php
        }
}
$end = microtime(TRUE);
error_log ($end - $begin ."\n", 3, 'test1.log');
?>

I ran each script in four different ways:[ul][li]on the command-line with output to /dev/null[/li][li] on the command-line with output to the console[/li][li]as a web script under PHP as an Apache module[/li][li]as a web script under PHP as a CGI script[/li][/ul]

I ran each script 25 times in each way.

On my LAMP (RH9/2.0.50/4.1.7/5.0.3) box, I have found that the code which does not context-switch is faster:

[tt] command-line command-line Apache Apache
(to /dev/null) (to console) module CGI

script 1 .45 .75 .18 2.19

script 2 .19 .30 .10 1.28

script 3 .11 .30 .10 .71[/tt]


Want the best answers? Ask the best questions!

TANSTAAFL!!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top