IT Community - Software Programming, Web Development and Technical Support

Website Performance Tips & Tricks

This is a discussion on Website Performance Tips & Tricks within the Web Design Help forums, part of the Web Development category; Optimize Your PHP Code * Introduce your PHP-code with <?php because a simple <? may cause interference with XML-...


Go Back   IT Community - Software Programming, Web Development and Technical Support > Web Development > Web Design Help

Register FAQ Members List Calendar Mark Forums Read
  22 links from elsewhere to this Post. Click to view. #41 (permalink)  
Old 08-17-2007, 10:02 PM
kathir kathir is offline
D-Web Trainee
 
Join Date: Feb 2007
Posts: 25
kathir is on a distinguished road
Default Re: Website Performance - Tips & Tricks

Optimize Your PHP Code

* Introduce your PHP-code with <?php because a simple <? may cause interference with XML-code.

* Prefer '.....' to "....." because the server side PHP engine parses everything it finds between the " " while it doesn't control what is written between the two single quotes.
But be careful if you use variables. You have to write

PHP Code:
<?php
echo 'This is my var:'$var'!!';
?>
instead of

PHP Code:
<?php
echo "This is my var: $var !!";
?>

By the way: <?php echo 'This is my var:',$var,'!!'; ?> should be some milliseconds faster than <?php echo 'This is my var:'.$var.'!!'; ?> (concatenated by a dot instead of the comma) and faster than <?php print 'This is my var:'.$var.'!!'; ?>

* Use SWITCH instead of IF when you have many options because it makes a lookup table and goes straight to the right case.

* Use IF instead of SWITCH if you have only few options because it evaluates every option until it finds a match.
Sometimes a trinary expression may simplifiy an IF/ELSE-expression because it reduces the written code:

PHP Code:
<?php
echo ($var==1)?'var is 1':'var is not 1';
?>
instead of

PHP Code:
<?php
if ($var==1){
    echo 
'var is 1';
}
else{
    echo 
'var is not 1';
}
?>
* Define the max-variables you use in your FOR-loops before starting the loop.
Prefer:

PHP Code:
<?php
$max
=filesize('myfile.dat'); //just to make an example
for ($i=0$i<$max$i++){
//your code
}
?>
to

PHP Code:
<?php
for ($i=0$i<filesize("myfile.dat"); $i++)
?>
So $max will be defined only once (and not as often as the loop is executed).

Thanks
-Kathir
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Sponsored Links
  #42 (permalink)  
Old 08-18-2007, 12:41 AM
vijayanand vijayanand is offline
D-Web Analyst
 
Join Date: Feb 2007
Posts: 293
vijayanand is on a distinguished road
Default Re: Website Performance - Tips & Tricks

Single Quotes and Double Quotes are Very Different

It never recommend using " (double quotes) when programming with PHP. Always use ' (single quotes) unless you need the features of " (double quotes). You might think it's much easier to write code as:

echo "Today is the $day of $month";

However, using single quotes forces variables to be outside the quotes; instead, you must use the period (.) to combine strings. It makes for faster coding but can be more difficult for other programmers to read. Let’s look at what would happen if we put an associative array value in the previous code:

echo "Today is the $date[‘day’] of $date[‘month’]";

we would receive a parse error and it would be harder for another team member to read. Two correct ways to write that line of code would be:

echo 'Today is the ' . $date[‘day’] . ' of ' . $date['month'];

and

echo "Today is the {$date['day']} of {$date['month']}";

These might not look as pretty as the original code, but syntactically they are both correct. Additionally, It is believed that the first method, with single quotes, is easier to read.

The use of single and double quotes also applies to associative arrays. Consider this code:

$SESSION[team] = $SESSION["old_team"];

One main problem exists in that line of code. The associative entry team on the left side needs to have single quotes around it; otherwise, PHP will think it’s a define and give you a warning message (only if error reporting is at maximum). It is recommend that the code should look like this:

$SESSION['team'] = $SESSION['old_team'];

From the above we had known the difference between single and double quotes as they pertain to strings.
__________________

J.Vijayanand
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #43 (permalink)  
Old 08-18-2007, 12:47 AM
kathir kathir is offline
D-Web Trainee
 
Join Date: Feb 2007
Posts: 25
kathir is on a distinguished road
Default Re: Website Performance - Tips & Tricks

Reduce Your PHP Code


Use HTML instead of PHP whenever possible. So you gain speed because the server side PHP engine parses only what it finds between <?php and ?>:

HTML Code:
<h3> Today </h3> <p>Today I met <?php echo $person; ?>. That was nice.</p>
instead of
PHP Code:
<?php
echo  "<h3>Today</h3><p>Today I met $person. That was nice.";
?>
Thanks
-Kathir
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #44 (permalink)  
Old 08-20-2007, 07:06 AM
kathir kathir is offline
D-Web Trainee
 
Join Date: Feb 2007
Posts: 25
kathir is on a distinguished road
Default Re: Website Performance - Tips & Tricks

Optimize Your MySQL Queries

* Select only the columns you need for your query. If you really don't want to select ALL the columns of your table don't digit SELECT * FROM tablename but write all the column names instead of "*" even if this means more writing work.

* Sort your data only if it's really necessary. It wastes a lot of time.

* Keep your filter conditions as easy as possible.

* Avoid mathematic MySQL-operations if possible. Leave them to PHP.

* Use connect only if you are sure that your pages will be connected only once and your user won't reconnect.

* Use pconnect for a persistant connection if you have several queries on your page.

* Use my_fetch_row() instead of my_fetch_array(). Sometimes this may be faster (I read somewhere).
my_fetch_rows() gives back an enumerated array:

PHP Code:
<?php
while($row mysql_fetch_rows($res)) echo $row[0], $row[1];
?>
my_fetch_array() is its extended version (the result array works with innumeric indices like above and with column names):

PHP Code:
<?php
while($row mysql_fetch_array($res))
    echo 
$row['columnname0'], $row['columnname1'];
?>
No idea about mysql_fetch_object() which works only with column names:

PHP Code:
<?php
while($row mysql_fetch_object($res))
    echo 
$row->columnname0$row->columnname1;
?>
Thanks
-Kathir
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #45 (permalink)  
Old 08-20-2007, 07:45 AM
ragavraj ragavraj is offline
D-Web Programmer
 
Join Date: Feb 2007
Posts: 92
ragavraj is on a distinguished road
Default Re: Website Performance - Tips & Tricks

Web Catching:-
It's a Technique to reduce load on backend servers by the way of serving up all static data requests(static HTML, Javascript and Image files).

Catching is particularly optimized for fast HTTP request handling. Thus when multiple clients request a certain object, such as an image file, the client will receive the response from that cache instead of your web servers.

The ability of Cache-Content is determined by the file's cache-control.
Thanks
R.Rajan
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #46 (permalink)  
Old 08-20-2007, 09:58 PM
ramkumaraol ramkumaraol is offline
D-Web Programmer
 
Join Date: Jul 2007
Posts: 98
ramkumaraol is on a distinguished road
Default Re: Website Performance Tips & Tricks

For classes with deep hierarchies, functions defined in derived classes (child classes) are invoked faster than those defined in base class (parent class). Consider replicating the most frequently used code in the base class in the derived classes too.

Thanks,
Ramkumar.B

Last edited by ramkumaraol : 08-20-2007 at 10:05 PM.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #47 (permalink)  
Old 08-20-2007, 10:04 PM
ramkumaraol ramkumaraol is offline
D-Web Programmer
 
Join Date: Jul 2007
Posts: 98
ramkumaraol is on a distinguished road
Default Re: Website Performance Tips & Tricks

Calling object methods (functions defined in a class) are about twice as slow as a normal function calls.

Inside a method (the following ratios are approximate only):

1. Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in a function.
2. Incrementing a global variable is 2 times slow than a local var.
3. Incrementing a object property (eg. $this->prop++) is 3 times slower than a local variable.
4. Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.
5. Just declaring a global variable without using it in a function also slows things down (by about the same amount as incrementing a local var). PHP probably does a check to see if the global exists.
6. Method invocation appears to be independent of the number of methods defined in the class because I added 10 more methods to the test class (before and after the test method) with no change in performance.
7. Methods in derived classes run faster than ones defined in the base class.
8. A function call with one parameter and an empty function body takes about the same time as doing 7-8 $localvar++ operations. A similar method call is of course about 15 $localvar++ operations.

Update: 11 July 2004: The above test was on PHP 4.0.4, about 3 years ago. I tested this again in PHP4.3.3 and calling a function now takes about 20 $localvar++ operations, and calling a method takes about 30 $localvar++ operations. This could be because $localvar++ runs faster now, or functions are slower.

Thanks,
Ramkumar.B
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #48 (permalink)  
Old 08-20-2007, 11:16 PM
velhari velhari is offline
D-Web Programmer
 
Join Date: Mar 2007
Location: Chennai
Posts: 67
velhari is on a distinguished road
Send a message via AIM to velhari
Thumbs up Re: Website Performance Tips & Tricks

Move Script Tags to Bottom Instead of Head Section:
This is one of the technique to improve the website performance.
Whenever a browser encounters javascript, it halts the stack of Yet to be performed HTTP Requests until the script has finished parsing and executing.

From the users perspective view, the page starts rendering as soon as possible, even when all images haven't loaded yet. In order to acheive this, we need to make sure that CSS get loaded as EARLY as possible and Javascript as LATE as Possible. so move all <script> tags to bottom of the page instead of head section where they usually have.
Note:-
Not all JS can be moved to the bottom of page. The script needs to be written as proper progressive enhancement for this technique to work.
__________________
Regards,
VELHARI
I am not totally useless. I can be used for a bad example
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #49 (permalink)  
Old 08-20-2007, 11:33 PM
vijayanand vijayanand is offline
D-Web Analyst
 
Join Date: Feb 2007
Posts: 293
vijayanand is on a distinguished road
Default Re: Website Performance Tips & Tricks

Query optimization

Minimizing the result set in a DB Query will decrease the maximum execution time.
For example to select only id & name of a member, rather than using the code like
select * from member where member_id='some number';
we can use the query like the following
select id,name from member where member_id='some number';

This will surely increase the performance of the page.
__________________

J.Vijayanand
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #50 (permalink)  
Old 08-20-2007, 11:43 PM
vijayanand vijayanand is offline
D-Web Analyst
 
Join Date: Feb 2007
Posts: 293
vijayanand is on a distinguished road
Default Re: Website Performance Tips & Tricks

Safe queries

A safe query will not return an error message that may reveal path information or give hackers accidental insider information. Certainly, security by obscurity is not an effective measure, but reducing error messages at the user end is desired once your site is launched.

Our first function performs the actual query using msyql_query. If the query string is empty it will return false.

PHP Code:
function safeQuery($query='')
{
    global 
$db;
    if (!
$query) return false;    
    return 
mysql_query($query$db->link);

The next two sample functions are our means for performing queries. Note that our fetchArray() function will return an array of results while the fetchRow() function will simply return a row. If either function returns no results FALSE will be returned.

PHP Code:
// returns an array of records
function fetchArray($query='')
{
    if (
$result safeQuery($query)) {
        if (
mysql_num_rows($result) > 0) {
            while (
$arr mysql_fetch_assoc($result)) $rows[] = $arr;
            return 
$rows;
        }
    }
    return 
false;


PHP Code:
// returns a single record
function fetchRecord($query='')
{    
    if (
$row safeQuery($query)) {
        if (
mysql_num_rows($row) > 0) {
            return 
mysql_fetch_assoc($row);
        }
    }
    return 
false;

Now, with one simple line of code we can perform our query to return our predicted results.

PHP Code:
$results fetchArray("SELECT id,field1 FROM records");

// sample output results
if (!$results) {
    echo 
'No results.';
} else {
    
// loop the data
    
foreach ($results as $result) {
        echo 
$result['id'] . ' ' $result['field1'];
    }

With this approach you can also define your queries more specifically for INSERT, DELETE, etc. and/or for repetitive tasks. Once you have a group of functions you are comfortable with you can recycle them in other projects.
__________________

J.Vijayanand
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #51 (permalink)  
Old 08-20-2007, 11:55 PM
velhari velhari is offline
D-Web Programmer
 
Join Date: Mar 2007
Location: Chennai
Posts: 67
velhari is on a distinguished road
Send a message via AIM to velhari
Default Re: Website Performance Tips & Tricks

Duplicate Scripts:
This is also one of the reason for to reduce the performance of the website and of course you might think its an unusual thing.
But it produce to creating the Unnecessary HTTP Request and wasting time in Javascript Execution.
Here Unnecessary HTTP Request doenot occur in firefox provided the script is cacheable but it happens in IE.

In IE, if an External script is included twice means, and that the script is not cacheable, it generates two HTTP Request during page loading. Even the script is cacheable means extra HTTP Request occur when the user reloads the page.
In addition to generating waste HTTP Request, time is wasted in evaluating the Script multiple times.

There are two possible situation for this to happen.
  1. Team size
  2. Number of Scripts
So to avoid this kind of situation, we need to maintain the script redundancy check system
__________________
Regards,
VELHARI
I am not totally useless. I can be used for a bad example
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #52 (permalink)  
Old 08-20-2007, 11:59 PM
vijayanand vijayanand is offline
D-Web Analyst
 
Join Date: Feb 2007
Posts: 293
vijayanand is on a distinguished road
Default Re: Website Performance Tips & Tricks

Template systems

Template systems provide a different type of caching. Content caching. Template systems work well in a situation where there is static data on one or many of your pages that doesn’t have to be reloaded. Caching systems also provide a separation of code and html, which will not only improve completion time of the overall project, but make it easier for future improvments. Most template systems for php are available for free(like smarty ect..).
__________________

J.Vijayanand
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #53 (permalink)  
Old 08-21-2007, 12:10 AM
vijayanand vijayanand is offline
D-Web Analyst
 
Join Date: Feb 2007
Posts: 293
vijayanand is on a distinguished road
Default Re: Website Performance Tips & Tricks

PHP variables that can be set

variables_order = ‘GPC’
register_argc_argv = ‘Off’
register_globals = ‘Off’ (this is a good idea to keep off for security purposes as well)
always_populate_raw_post_data = ‘Off’
magic_quotes_gpc = ‘Off’

Disable Error Logging. This is a good idea to keep on when you are developing your scripts, but it has been known to decrease overall performance.

Use IP address to access your database. Although this is sometimes not possible, you will get a slight boost in lookup speed if the IP address is used to access your database rather than its hostname.
__________________

J.Vijayanand
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #54 (permalink)  
Old 08-21-2007, 12:28 AM
kathir kathir is offline
D-Web Trainee
 
Join Date: Feb 2007
Posts: 25
kathir is on a distinguished road
Default Re: Website Performance Tips & Tricks

Use output buffering

This will speed up your PHP code by 5-15% if you frequently print or echo in your code. When output buffering is enabled it pipes the output into a dynamically growing buffer and sends the buffer content with the output in one shot at the end of the script (or when you decide). Output buffering reduces networking overhead substantially at the cost of more memory and an increase in latency.

These are the main functions to control output buffering:
* ob_start() enables output buffering. (Output buffering supports multiple levels, that means you can call ob_start() several times.)
* ob_end_flush() sends the output buffer and disables output buffering.
* ob_end_clean() cleans the output buffer without sending it and disables output buffering.
* ob_get_contents() returns the current output buffer as a string that you can echo to send the accumulated output to the browser (after turning buffering off).
* int ob_get_length() returns the length of the output buffer.

An example:


PHP Code:
<?php
ob_start
(); //start buffering
ob_implicit_flush(0); //turn off implicit flushing
//now your output stuff:
echo 'This is the 1st line with compressed output.';
$str='<br /> This is the 2nd line.';
echo 
$str;
$var1=10;
$var2=7;
$var3=$var1-$var2;
echo 
'<br /> This is the ',$var3'rd line.';
$contents ob_get_contents(); //if you don't add "ob_end_clean()" all that you
wanted to echo out will be echoed out NOW
ob_end_clean
(); //if you add this line nothing will be echoed out, only if you add after this line "echo $contents" the content will be echoed out.
?>
If your version of PHP is compiled with zlib support and is 4.0.4 or higher, you can also try this:

PHP Code:
<?php
ob_start
('ob_gzhandler');
// rest of your script
?>
Thanks
-Kathir
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #55 (permalink)  
Old 08-21-2007, 01:53 AM
vijayanand vijayanand is offline
D-Web Analyst
 
Join Date: Feb 2007
Posts: 293
vijayanand is on a distinguished road
Default Re: Website Performance Tips & Tricks

Tips for increase the site performance
  1. General rule of thumb for hardware upgrades: For PHP scripts, the main bottleneck is the CPU. For static HTML/images, the bottleneck is RAM and the network. According to Compaq benchmarks in 1999 (the original article is lost due to bitrot), a slow 400 Mhz Pentium can saturate a T3 line (that's 45 Mbps) with static HTML pages.
  2. A PHP script will be served at least 2-10 times slower than a static HTML page by Apache. Try to use more static HTML pages and fewer scripts.
__________________

J.Vijayanand
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #56 (permalink)  
Old 08-21-2007, 02:22 AM
kathir kathir is offline
D-Web Trainee
 
Join Date: Feb 2007
Posts: 25
kathir is on a distinguished road
Default Re: Website Performance Tips & Tricks

Compress your data

Many browsers support transparent compression using gzip. The server detects that the browser supports gzip encoding, compresses and sends the data (using the Content-Encoding: gzip header line) in spite of sending data in plain text form. When the compressed data arrives at the browser, it will be decompressed. This shortens the load time for the page.
Here is the code with the function that compresses the output:
PHP Code:
<?php
function compress_output($contents){
//tell the browser that gzip data will be sent:
header("Content-Encoding: gzip");
echo 
"\x1f\x8b\x08\x00\x00\x00\x00\x00";
$Size strlen($contents); 
/* figure out the size and CRC (Cyclic Redundancy
Check) of the original for later, if you want to know more about this read
Luis Argerich's article cited at the bottom of this chapter. That's where I found this code */
$Crc crc32($contents);
$contents gzcompress($contents9); // compress the data
echo $contents;
gzip_PrintFourChars($Crc);
gzip_PrintFourChars($Size);

function 
gzip_PrintFourChars($Val) {
for (
$i 0$i 4$i ++) {
echo 
chr($Val 256);
$Val floor($Val 256);
}
}
}
//check if the browser supports gzip encoding:
if(ereg('gzip, deflate',$HTTP_ACCEPT_ENCODING)){
compress_output();
}
else{
echo 
$contents;
}
?>
Thanks
-Kathir
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #57 (permalink)  
Old 08-21-2007, 05:04 AM
vijayanand vijayanand is offline
D-Web Analyst