This is a discussion on PHP Optimization Tips within the PHP Programming forums, part of the Web Development category; str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4 str_replace is faster than ...
| |||||||
| Register | FAQ | Members List | Calendar | Mark Forums Read |
| |||
| str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4 str_replace is faster than preg_replace... But from the link I have found - strtr is not 4x faster! The link gave me 3 wins for str_replace and 2 for strtr. Str_replace - Strtr -- Realtime test.
__________________ Thanks & Regards Sabari... Last edited by shiva : 11-06-2007 at 08:29 AM. |
| Sponsored Links |
| |||
| Hi sabari: Really this Topic is Outstanding and u analyzed the php from top to bottom. I am also eager to Join this topic to share what i know. For ($i=0;$i<=$1000;$i++){ } is better slower than for($i=1000;$i<=0;$i--){ } if chance we can use the reverse order to Better faster.
__________________ regards K.Lakshmanan [Web developer] Last edited by shiva : 11-06-2007 at 08:29 AM. |
| |||
| Tuning Your Web Server for PHP ------------------------------- Apache is available on both Unix and Windows. It is the most popular web server in the world. Apache 1.3 uses a pre-forking model for web serving. When Apache starts up, it creates multiple child processes that handle HTTP requests. The initial parent process acts like a guardian angel, making sure that all the child processes are working properly and coordinating everything. As more HTTP requests come in, more child processes are spawned to process them. As the HTTP requests slow down, the parent will kill the idle child processes, freeing up resources for other processes. The beauty of this scheme is that it makes Apache extremely robust. Even if a child process crashes, the parent and the other child processes are insulated from the crashing child. Apache is configured using the httpd.conf file. The following parameters are particularly important in configuring child processes: MaxClients(256) StartServers(5) MinSpareServers(5) MaxSpareServers(10) MaxRequestsPerChild(0)
__________________ With, J. Jeyaseelan Everything Possible Last edited by shiva : 11-06-2007 at 08:28 AM. |
| |||
| Hi, 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. Regards, R.Kamalakannan. Last edited by shiva : 11-06-2007 at 08:28 AM. |
| |||
| Hi, Use ob_start() at the beginning of your code. This gives you a 5-15% boost in speed for free on Apache. You can also use gzip compression for extra fast downloads (this requires spare CPU cycles). Regards, R.Kamalakannan. Last edited by shiva : 11-06-2007 at 08:27 AM. |
| |||
| Hi, Handy New function in PHP file_put_contents() Code: //Slow to openning a file and write the content in to a file
$fp = fopen("FilePath", "a");
fwrite($fp, $somecontent)
fclose($fp); Code: // The simpler & faster to write or append the data in to a file
$data = file_put_contents("FilePath"); R.Gopi Last edited by shiva : 11-06-2007 at 08:27 AM. |
| |||
| Fast UU encoding/decoding mechanism. UU Encoding FUnction Code: Syntax string convert_uuencode ( string $data ) Uuencode translates all strings (including binary's ones) into printable characters, making them safe for network transmissions. Uuencoded data is about 35% larger than the original. Example: Code: <?php $some_string = "test\ntext text\r\n"; echo convert_uuencode($some_string); ?> UU Decoding FUnction Code: Syntax string convert_uudecode ( string $data ) Example: Code: <?php
/* Can you imagine what this will print? :) */
echo convert_uudecode("+22!L;W9E(%!(4\"$`\n`");
?> Thanks, R.Gopi Last edited by shiva : 11-06-2007 at 08:30 AM. |
| |||
| Hi, Fast Build GET/POST query based on associated array. http://www.discussweb.com/php-progra...ted-array.html Thanks, R.Gopi Last edited by shiva : 11-06-2007 at 08:30 AM. |
| |||
| There are a number of tricks that you can use to squeeze the last bit of performance from your scripts. These tricks won't make your applications much faster, but can give you that little edge in performance you may be looking for. More importantly it may give you insight into how PHP internals works allowing you to write code that can be executed in more optimal fashion by the Zend Engine. Please keep in mind that these are not the 1st optimization you should perform. There are some far easier and more performance advantageous tricks, however once those are exhausted and you don't feel like turning to C, these maybe tricks you would want to consider. So, without further ado... 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 a 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.
__________________ Thanks & Regards Sabari... |
| |||
| Incrementing and Decrementing 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... |
| |||
| Printing Text When it comes to printing text to screen PHP has so many methodologies to do it, not many users even know all of them. This tends to result in people using output methods they are already familiar from other languages. While this is certainly an understandable approach it is often not best one as far as performance in concerned. print vs echo Even both of these output mechanism are language constructs, if you benchmark the two you will quickly discover that print() is slower then echo(). The reason for that is quite simple, print function will return a status indicating if it was successful or not, while echo simply print the text and nothing more. Since in most cases (haven't seen one yet) this status is not necessary and is almost never used it is pointless and simply adds unnecessary overhead. printf Using printf() is slow for multitude of reasons and I would strongly discourage it's usage unless you absolutely need to use the functionality this function offers. Unlike print and echo printf() is a function with associated function execution overhead. More over printf() is designed to support various formatting schemes that for the most part are not needed in a language that is typeless and will automatically do the necessary type conversions. To handle formatting printf() needs to scan the specified string for special formatting code that are to be replaced with variables. As you can probably imagine that is quite slow and rather inefficient. heredoc This output method comes to PHP from PERL and like most features adopted from other languages it's not very friendly as far as performance is concerned. While this method allows you to easily output large chunks of text while preserving things like newlines and even allow for variable handling inside the text block this is quite slow and there are better ways to do that. Performance wise this is just marginally faster then printf() however it does not offer nearly as much functionality. ?> <? When you need to output a large or even a medium sized static bit of text it is faster and simpler to put it outside the of PHP. This will make the PHP's parser effectively skipover this bit of text and output it as is without any overhead. You should be careful however and not use this for many small strings in between PHP code as multiple context switches between PHP and plain text will ebb away at the performance gained by not having PHP print the text via one of it's functions or constructs.
__________________ Thanks & Regards Sabari... |
| |||
| Regular Expression Many scripts tend to reply on regular expression to validate the input specified by user. While validating input is a superb idea, doing so via regular expression can be quite slow. In many cases the process of validation merely involved checking the source string against a certain character list such as A-Z or 0-9, etc... Instead of using regex in many instances you can instead use the ctype extension (enabled by default since PHP 4.2.0) to do the same. The ctype extension offers a series of function wrappers around C's is*() function that check whether a particular character is within a certain range. Unlike the C function that can only work a character at a time, PHP function can operate on entire strings and are far faster then equivalent regular expressions. Ex. preg_match("![0-9]+!", $foo); vs ctype_digit($foo);
__________________ Thanks & Regards Sabari... |
| |||
| Array Searching Another common operation in PHP scripts is array searching. This process can be quite slow as regular search mechanism such as in_array() or manuall implementation work by itterating through the entire array. This can be quite a performance hit if you are searching through a large array or need to perform the searches frequently. So what can you do? Well, you can do a trick that relies upon the way that Zend Engine stores array data. Internally arrays are stored inside hash tables when they array element (key) is the key of the hashtables used to find the data and result is the value associated with that key. Since hashtable lookups are quite fast, you can simplify array searching by making the data you intend to search through the key of the array, then searching for the data is as simple as $value = isset($foo[$bar])) ? $foo[$bar] : NULL;. This searching mechanism is way faster then manual array iteration, even though having string keys maybe more memory intensive then using simple numeric keys. Ex. $keys = array("apples", "oranges", "mangoes", "tomatoes", "pickles"); if (in_array('mangoes', $keys)) { ... } vs $keys = array("apples" => 1, "oranges" => 1, "mangoes" => 1, "tomatoes" => 1, "pickles" => 1); if (isset($keys['mangoes'])) { ... } The bottom search mechanism is roughly 3 times faster
__________________ Thanks & Regards Sabari... |
| |||
| Another useful optimization technique for PHP would be changing how you use 'for' loops. Most people use the obligatory (assuming $j is an array): for ($i = 0; $i < count($j); $i++) { ... } There are two obvious performance hits here. The first, as mentioned in your blog, is the post-increment. You can EITHER do ++$i, or you can change it to '$i = $i + 1', respectively. The second thing would be to move the count() function out of the middle of the 'for' loop, to avoid the multiple calls on count(). So, the above example could easily written out in a new fashion: for ($i = 0, $k = count($j); $i < $k; $i = $i + 1) { ... } I have found that in my code writing I am able to shave a few microseconds off it's execution; on bigger, more robust applications, those microseconds have added up to whole seconds!
__________________ Thanks & Regards Sabari... |
| |||
| When trying to call mysql_fetch_array() will return an array with both index types, mysql_fetch_assoc() will not return numerical indexed array, mysql_fetch_row() will return just numerical indexed array
__________________ With, J. Jeyaseelan Everything Possible |
| |||
| 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 |
| |||
| Tips: 1. Keep blocks of PHP script together. Each switch between PHP script and HTML causes the compiler to stop and start processing. 2. Be careful of string concatenation as the size of the string grows. As the string grows through concatenation, it is copied to a new location in memory each time.
__________________ J.Vijayanand |
| |||
| Tips: 1. Reduce the use of global variables. 2. Reduce the number of include files used on a page. Also, segment and categorize functions in commonly used include files.
__________________ J.Vijayanand |
![]() |
| 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 | |