Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old Feb 9th, 2011, 10:30 PM   #1
Paulette
Newbie
 
Join Date: Feb 2011
Posts: 1
Rep Power: 0 Paulette is on a distinguished road
Some PHP Tips

- If a method can be static‚ declare it static. Speed improvement is by a factor of 4.

- echo is faster than print.

- Use echo’s multiple parameters instead of string concatenation.

- Set the maxvalue for your for-loops before and not in the loop.

- Unset your variables to free memory‚ especially large arrays.

- Avoid magic like __get‚ __set‚ __autoload

- require_once() is expensive

- Use full paths in includes and requires‚ less time spent on resolving the OS paths.

- If you need to find out the time when the script started executing‚ $_SERVER[’REQUEST_TIME’] is preferred to time()

- See if you can use strncasecmp‚ strpbrk and stripos instead of regex

- str_replace is faster than preg_replace‚ but strtr is faster than str_replace by a factor of 4

- If the function‚ such as string replacement function‚ accepts both arrays and single characters as arguments‚ and if your argument list is not too long‚ consider writing a few redundant replacement statements‚ passing one character at a time‚ instead of one line of code that accepts arrays as search and replace arguments.

- It’s better to use select statements than multi if‚ else if‚ statements.

- Error suppression with @ is very slow.

- Turn on apache’s mod_deflate

- Close your database connections when you’re done with them

- $row[’id’] is 7 times faster than $row[id]

- Error messages are expensive

- Do not use functions inside of for loop‚ such as for ($x=0; $x < count($array); $x) The count() function gets called each time.

- Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in a function.

- Incrementing a global variable is 2 times slow than a local var.

- Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable.

- Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.

- 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.

- 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.

- Methods in derived classes run faster than ones defined in the base class.

- 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.

- Surrounding your string by ’ instead of " will make things interpret a little faster since php looks for variables inside "..." but not inside ’...’. Of course you can only do this when you don’t need to have variables in the string.

- When echoing strings it’s faster to separate them by comma instead of dot. Note: This only works with echo‚ which is a function that can take several strings as arguments.

- 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.

- Your PHP scripts are recompiled every time unless the scripts are cached. Install a PHP caching product to typically increase performance by 25-100% by removing compile times.

- Cache as much as possible. Use memcached - memcached is a high-performance memory object caching system intended to speed up dynamic web applications by alleviating database load. OP code caches are useful so that your script does not have to be compiled on every request

- When working with strings and you need to check that the string is either of a certain length you’d understandably would want to use the strlen() function. This function is pretty quick since it’s operation does not perform any calculation but merely return the already known length of a string available in the zval structure (internal C struct used to store variables in PHP). However because strlen() is a function it is still somewhat slow because the function call requires several operations such as lowercase & hashtable lookup followed by the execution of said function. In some instance you can improve the speed of your code by using an isset() trick.

Ex.
if (strlen($foo) < 5) { echo "Foo is too short"; }
vs.
if (!isset($foo{5})) { echo "Foo is too short"; }


Calling isset() happens to be faster then strlen() because unlike strlen()‚ isset() is a language construct and not a function meaning that it’s execution does not require function lookups and lowercase. This means you have virtually no overhead on top of the actual code that determines the string’s length.

- When incrementing or decrementing the value of the variable $i++ happens to be a tad slower then ++$i. This is something PHP specific and does not apply to other languages‚ so don’t go modifying your C or Java code thinking it’ll suddenly become faster‚ it won’t. ++$i happens to be faster in PHP because instead of 4 opcodes used for $i++ you only need 3. Post incrementation actually causes in the creation of a temporary var that is then incremented. While pre-incrementation increases the original value directly. This is one of the optimization that opcode optimized like Zend’s PHP optimizer. It is a still a good idea to keep in mind since not all opcode optimizers perform this optimization and there are plenty of ISPs and servers running without an opcode optimizer.

- Not everything has to be OOP‚ often it is too much overhead‚ each method and object call consumes a lot of memory.

- Do not implement every data structure as a class‚ arrays are useful‚ too

- Don’t split methods too much‚ think‚ which code you will really re-use
You can always split the code of a method later‚ when needed

- Make use of the countless predefined functions

- If you have very time consuming functions in your code‚ consider writing them as C extensions.

- Profile your code. A profiler shows you‚ which parts of your code consumes how many time. The Xdebug debugger already contains a profiler. Profiling shows you the bottlenecks in overview

- mod_gzip which is available as an Apache module compresses your data on the fly and can reduce the data to transfer up to 80%
__________________
Catalytic Converter|Fuel Pump
Paulette is offline   Reply With Quote
Old Feb 11th, 2011, 11:38 AM   #2
titaniumdecoy
Programming Guru

 
titaniumdecoy's Avatar
 
Join Date: Nov 2005
Location: California
Posts: 1,535
Rep Power: 14 titaniumdecoy will become famous soon enoughtitaniumdecoy will become famous soon enough
Send a message via AIM to titaniumdecoy
Re: Some PHP Tips

It would be nice to see sources for all of your claims.
titaniumdecoy is offline   Reply With Quote
Old Feb 13th, 2011, 9:13 PM   #3
aje
Newbie
 
aje's Avatar
 
Join Date: Dec 2010
Posts: 4
Rep Power: 0 aje is on a distinguished road
Re: Some PHP Tips

I would have to agree with titaniumdecoy, certain arguments of yours such as single quotes being faster than double were only true before 4.3, which stopped being supported many years ago. In fact single quotes are checked as well, as how would the parser find out if an escaped single quote is escaped?
aje is offline   Reply With Quote
Old Mar 16th, 2011, 12:04 AM   #4
mort03crow
Newbie
 
Join Date: Mar 2011
Posts: 5
Rep Power: 0 mort03crow is an unknown quantity at this point
Re: Some PHP Tips

best tips you have shared
i am also working on PHP language
__________________
business phone systems
800 number
mort03crow is offline   Reply With Quote
Old Mar 16th, 2011, 3:52 AM   #5
alexsmth114
Newbie
 
Join Date: Mar 2011
Posts: 15
Rep Power: 0 alexsmth114 is on a distinguished road
Re: Some PHP Tips

Some really nice tips, keep them coming!!..
alexsmth114 is offline   Reply With Quote
Old Jun 22nd, 2011, 2:28 AM   #6
danieljames123
Programmer
 
Join Date: May 2011
Posts: 60
Rep Power: 7 danieljames123 is on a distinguished road
Re: Some PHP Tips

Great post! Really useful for a beginner and current user. High performance and reliability and Low development and maintenance cost are main thing in it and thats why many company turn on it.
danieljames123 is offline   Reply With Quote
Old Aug 5th, 2011, 6:50 AM   #7
manimoor
Newbie
 
Join Date: Aug 2011
Posts: 3
Rep Power: 0 manimoor is on a distinguished road
Some PHP Tips

hi..here provides php tips for beginners,
PHP, a popular server side language is now mandatory for every web developer who wants to make a mark in this profession. Though PHP language is a new introduction in the market and a bit difficult than HTML or other basic languages, there is nothing to consider it as a rocket science.

With proper training session and PHP tutorial, one can easily use PHP for web development. Beginners, who are not much familiar with the intricacies of PHP, may glance through some tips to ease their task.

To avoid the fear or the hesitation of using PHP language, it is always better for you to use this language as often as you can. Remember, a training module can help you in understanding the functionalities of language or the details of it.

example:
a sample register shutdown function

<?php
function browserClosed()
{
//we can specify the logout actions on browser closing
echo "logout";
}
?>

register_shutdown_function('browserClosed');
__________________
Cegonsoft
manimoor is offline   Reply With Quote
Old Sep 19th, 2011, 6:58 AM   #8
willsmith12
Newbie
 
Join Date: Sep 2011
Posts: 4
Rep Power: 0 willsmith12 is on a distinguished road
Some PHP Tips

Hi... I provides 50 SEO tips here......

echo is faster than print.
Wrap your string in single quotes (’) instead of double quotes (”) is faster because PHP searches for variables inside “…” and not in ‘…’, use this when you’re not using variables you need evaluating in your string.
Use sprintf instead of variables contained in double quotes, it’s about 10x faster.
Use echo’s multiple parameters (or stacked) instead of string concatenation.
Use pre-calculations, set the maximum value for your for-loops before and not in the loop. ie: for ($x=0; $x < count($array); $x), this calls the count() function each time, use $max=count($array) instead before the for-loop starts.
Unset or null your variables to free memory, especially large arrays.
Avoid magic like __get, __set, __autoload.
Use require() instead of require_once() where possible.
Use full paths in includes and requires, less time spent on resolving the OS paths.
require() and include() are identical in every way except require halts if the file is missing. Performance wise there is very little difference.
Since PHP5, the time of when the script started executing can be found in $_SERVER[’REQUEST_TIME’], use this instead of time() or microtime().
PCRE regex is quicker than EREG, but always see if you can use quicker native functions such as strncasecmp, strpbrk and stripos instead.
When parsing with XML in PHP try xml2array, which makes use of the PHP XML functions, for HTML you can try PHP’s DOM document or DOM XML in PHP4.
str_replace is faster than preg_replace, str_replace is best overall, however strtr is sometimes quicker with larger strings. Using array() inside str_replace is usually quicker than multiple str_replace.
“else if” statements are faster than select statements aka case/switch.
Error suppression with @ is very slow.
To reduce bandwidth usage turn on mod_deflate in Apache v2 or for Apache v1 try mod_gzip.
Close your database connections when you’re done with them.
$row[’id’] is 7 times faster than $row[id], because if you don’t supply quotes it has to guess which index you meant, assuming you didn’t mean a constant.
Use <?php … ?> tags when declaring PHP as all other styles are depreciated, including short tags.
Use strict code, avoid suppressing errors, notices and warnings thus resulting in cleaner code and less overheads. Consider having error_reporting(E_ALL) always on.
PHP scripts are be served at 2-10 times slower by Apache httpd than a static page. Try to use static pages instead of server side scripts.
PHP scripts (unless cached) are compiled on the fly every time you call them. Install a PHP caching product (such as memcached or eAccelerator or Turck MMCache) to typically increase performance by 25-100% by removing compile times. You can even setup eAccelerator on cPanel using EasyApache3.
An alternative caching technique when you have pages that don’t change too frequently is to cache the HTML output of your PHP pages. Try Smarty or Cache Lite.
Use isset where possible in replace of strlen. (ie: if (strlen($foo) < 5) { echo “Foo is too short”; } vs. if (!isset($foo{5})) { echo “Foo is too short”; } ).
++$i is faster than $ i++, so use pre-increment where possible.
Make use of the countless predefined functions of PHP, don’t attempt to build your own as the native ones will be far quicker; if you have very time and resource consuming functions, consider writing them as C extensions or modules.
Profile your code. A profiler shows you, which parts of your code consumes how many time. The Xdebug debugger already contains a profiler. Profiling shows you the bottlenecks in overview.
Document your code.
Learn the difference between good and bad code.
Stick to coding standards, it will make it easier for you to understand other people’s code and other people will be able to understand yours.
Separate code, content and presentation: keep your PHP code separate from your HTML.
Don’t bother using complex template systems such as Smarty, use the one that’s included in PHP already, see ob_get_contents and extract, and simply pull the data from your database.
Never trust variables coming from user land (such as from $_POST) use mysql_real_escape_string when using mysql, and htmlspecialchars when outputting as HTML.
For security reasons never have anything that could expose information about paths, extensions and configuration, such as display_errors or phpinfo() in your webroot.
Turn off register_globals (it’s disabled by default for a reason!). No script at production level should need this enabled as it is a security risk. Fix any scripts that require it on, and fix any scripts that require it off using unregister_globals(). Do this now, as it’s set to be removed in PHP6.
Avoid using plain text when storing and evaluating passwords to avoid exposure, instead use a hash, such as an md5 hash.
Use ip2long() and long2ip() to store IP addresses as integers instead of strings.
You can avoid reinventing the wheel by using the PEAR project, giving you existing code of a high standard.
When using header(’Location: ‘.$url); remember to follow it with a die(); as the script continues to run even though the location has changed or avoid using it all together where possible.
In OOP, if a method can be a static method, declare it static. Speed improvement is by a factor of 4..
Incrementing a local variable in an OOP method is the fastest. Nearly the same as calling a local variable in a function and incrementing a global variable is 2 times slow than a local variable.
Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable.
Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.
Just declaring a global variable without using it in a function slows things down (by about the same amount as incrementing a local var). PHP probably does a check to see if the global exists.
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.
Methods in derived classes run faster than ones defined in the base class.
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.
Not everything has to be OOP, often it is just overhead, each method and object call consumes a lot of memory.
Never trust user data, escape your strings that you use in SQL queries using mysql_real_escape_string, instead of mysql_escape_string or addslashes. Also note that if magic_quotes_gpc is enabled you should use stripslashes first.
Avoid the PHP mail() function header injection issue.
Unset your database variables (the password at a minimum), you shouldn’t need it after you make the database connection.
RTFM! PHP offers a fantastic manual, possibly one of the best out there, which makes it a very hands on language, providing working examples and talking in plain English. Please USE IT!


<snipped fake signature>
__________________
software testing firm

Last edited by Ancient Dragon; Sep 19th, 2011 at 8:07 AM. Reason: snipped fake signature
willsmith12 is offline   Reply With Quote
Old Oct 30th, 2011, 11:40 PM   #9
hirephpexpert
Newbie
 
Join Date: Oct 2011
Posts: 2
Rep Power: 0 hirephpexpert is on a distinguished road
Re: Some PHP Tips

I just first time using this post but I got relevant information about PHP which I was know about that, I am sure these tips will be useful to everyone, excellent information for new learner.
hirephpexpert is offline   Reply With Quote
Old Nov 2nd, 2011, 8:36 AM   #10
jashandeep
SEO Expert
 
jashandeep's Avatar
 
Join Date: Oct 2011
Location: city:Mohali,Chandigarh,india
Posts: 113
Rep Power: 6 jashandeep is on a distinguished road
Send a message via Skype™ to jashandeep
Re: Some PHP Tips

Wow what a conclusion for PHP you have.I really appreciate you for your deep knowledge about PHP.
jashandeep is offline   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Do u know PHP Programming is Most Used Programming Language annaawills PHP 16 Aug 8th, 2010 6:26 PM
The Complete Reference - PHP Overmind Book Reviews 1 Dec 7th, 2009 9:16 PM
Php Tutorial 3 bulio PHP 4 Jul 16th, 2006 4:00 AM




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 5:34 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2017, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC