This is a discussion on PHP Optimization Tips within the PHP Programming forums, part of the Web Development category; Here listed the simple tips to optimize your php code * If a method can be static, declare it static. Speed ...
| |||||||
| Register | FAQ | Members List | Calendar | Mark Forums Read |
| |||
| Here listed the simple tips to optimize your php code * If a method can be static, declare it static. Speed improvement is by a factor of 4. * <em>echo</em> is faster than <em>print</em>. * 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.
__________________ Thanks & Regards Sabari... Last edited by Sabari : 11-02-2007 at 03:43 AM. |
| Sponsored Links |
| |||
| * 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
__________________ Thanks & Regards Sabari... Last edited by shiva : 11-06-2007 at 08:31 AM. |
| |||
| * 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
__________________ Thanks & Regards Sabari... Last edited by shiva : 11-06-2007 at 03:21 AM. |
| |||
| * 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. * 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%
__________________ Thanks & Regards Sabari... Last edited by shiva : 11-06-2007 at 08:32 AM. |
| |||
| * 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.
__________________ Thanks & Regards Sabari... Last edited by shiva : 11-06-2007 at 08:32 AM. |
| |||
| * 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.
__________________ Thanks & Regards Sabari... Last edited by shiva : 11-06-2007 at 08:32 AM. |
| |||
| * 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"; }<br /> 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.
__________________ Thanks & Regards Sabari... Last edited by shiva : 11-06-2007 at 08:33 AM. |
| |||
| * 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
__________________ Thanks & Regards Sabari... Last edited by shiva : 11-06-2007 at 08:33 AM. |
| |||
| Hi Sabari, Generally PHP is a very fast programming language, but there is more to optimizing PHP than just speed of code execution. So we have to tune and optimize our PHP scripts so they run even faster. I think it should be done not only in PHP but with web servers, DB servers and Proper network, proper channels to connect net., etc...
__________________ With, J. Jeyaseelan Everything Possible Last edited by shiva : 11-06-2007 at 08:33 AM. |
| |||
| you are correct Jeyaseelan, we need to discuss about those things also not only in PHP. please post what ever things you know related to this.
__________________ Thanks & Regards Sabari... Last edited by shiva : 11-06-2007 at 08:34 AM. |
| |||
| When to Start Optimizing? If your programming team's coding is of a high quality to begin with, and you already have a good feel of the performance parameters of your application. Otherwise you are exposing yourselves to the risk of having to rewrite substantial portions of your code after testing. My advice is that before you design a software application, you should do some basic benchmarks on the hardware and software to get a feel for the maximum performance you might be able to achieve. Then as you design and code the application, keep the desired performance parameters in mind, because at every step of the way there will be tradeoffs between performance, availability, security and flexibility. Also choose good test data. If your database is expected to hold 100,000 records, avoid testing with only a 100 record database – you will regret it. This once happened to one of the programmers in my company; we did not detect the slow code until much later, causing a lot of wasted time as we had to rewrite a lot of code that worked but did not scale.
__________________ With, J. Jeyaseelan Everything Possible Last edited by shiva : 11-06-2007 at 08:34 AM. |
| |||
| String: As you may know strings can be defined using two styles, the single and the double quote. For best performance use single quoted strings. This is faster as the single quoted strings are not parsed while the double quoted strings are parsed for special characters and variables. Example : This : $a = '123' . $b ; is faster than this : $a = "123$b"; Last edited by shiva : 11-06-2007 at 08:35 AM. |
| |||
| Optimizing if statements For simple if statements you can always use the ? operator. Example code : if ( $b > 1 ) $a = true; else $a = false; is better & faster than this : $a = $b>1 ? true : false; Last edited by shiva : 11-06-2007 at 08:35 AM. |
| |||
| Optimizing loops In general for ($i=0;.....) is faster than for each(...) but of course for each is much easier to use when you code. Here is an alternative that is faster from both : while ( $val = array_shift($array) ) echo $val; This example will extract the first value from the array so it will also free up some memory in the process. Last edited by shiva : 11-06-2007 at 08:36 AM. |
| |||
| It’s the time to write another php&mysql trick. This time I’ll tell how to count the rows resulted after a “SELECT” query. Many of us use simply the php method, like in the next example : $result = mysql_query("SELECT * FROM table"); $rows=mysql_num_rows($result) ; But it can be done easier, using only a mysql query who returns the exact number of rows. $result = mysql_query("SELECT count(*) FROM table"); $rows = mysql_result($result, 0); It’s a lot simpler for the computer to make this way beucase the query will load the $result with a big table, which consumes memory and processor’s time to manipulate, and on a big website, it would cost some time (not only few miliseconds) to process. Last edited by shiva : 11-06-2007 at 08:36 AM. |
| |||
| Hi, Reference Tricks References can be used to simply & accelerate access to multi-dimensional arrays. Code: $a['b']['c'] = array(); // slow 2 extra hash lookups per access for($i = 0; $i < 5; $i++) $a['b']['c'][$i] = $i; Code: // much faster reference based approach $ref =& $a['b']['c']; for($i = 0; $i < 5; $i++) $ref[$i] = $i; R.Gopi. Last edited by shiva : 11-06-2007 at 08:36 AM. |
| |||
| Hi, Don’t Reinvent the Wheel in PHP PHP have includes hundreds of functions, always to be check if the desired operation is already natively implemented. Code: //Slow to get the content from file
$data = '';
$fp = fopen("FilePath", "r");
while ($fp && !feof($fp)) {
$data .= fread($fp, 1024);
} fclose($fp); Code: // The much simpler & faster
$data = file_get_contents("FilePath"); Thanks, R.Gopi Last edited by shiva : 11-06-2007 at 08:37 AM. |
| |||
| Do not use functions inside of for loop, such as for ($x=0; $x < count($array); $x) The count() function gets called each time. for($i = 0; $c = count($array); $i < $c; $i++) I've been told that this is quite efficient. for($i = 0, $c = count($array); $i < $c; $i++) Initialize multiple variables only happens at beginning of the loop they should be comma separated As mentioned it is the same as this. $c = count($array); for($i = 0; $i < $c; $i++) This method is what you want to avoid.for($i = 0; $i < count($array); $i++)
__________________ Thanks & Regards Sabari... Last edited by shiva : 11-06-2007 at 08:37 AM. |
| |||
| if you're using header("Location:url"); make sure you follow it with a die(); SQL Injection has nothing to do with optimization (I'm thinking of speed here), but yeah, still important. Surprised there was nothing about concatenation for strings. Overall, a decent reminder list for all of us who think we remember it all.
__________________ Thanks & Regards Sabari... Last edited by shiva : 11-06-2007 at 08:38 AM. |
![]() |
| Thread Tools | |
| Display Modes | |
| |
LinkBacks (?)
LinkBack to this Thread: http://www.discussweb.com/php-programming/4357-php-optimization-tips.html | |||
| Posted By | For | Type | Date |
| The Storyteller | This thread | Refback | 11-30-2007 07:09 AM |
| del.icio.us/subscriptions/KoerPoiss | This thread | Refback | 11-30-2007 06:47 AM |
| Planet PHP Japan | This thread | Refback | 11-30-2007 04:35 AM |
Similar Threads | ||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| All You Need for Search Engine Optimization (SEO) | vozduhh | Search Engine Optimization | 1 | 02-20-2008 11:40 AM |
| SEO optimization question.? | navjeet | Search Engine Optimization | 1 | 09-04-2007 11:54 AM |
| Image Alt Tag Optimization Tips | vadivelanvaidyanathan | Search Engine Optimization | 0 | 03-30-2007 03:02 AM |
| Title Tag Optimization Tips | vadivelanvaidyanathan | Search Engine Optimization | 0 | 03-30-2007 02:58 AM |
| SEO Optimization - Page Title | drecko | Search Engine Optimization | 2 | 02-19-2007 01:28 AM |