Last active
March 12, 2023 18:33
-
-
Save undefinedzain/59253876994d79d5f70b11f7745b4217 to your computer and use it in GitHub Desktop.
63 Tips for speeding up your php application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<body> | |
<p>Here are Webber’s points:</p> | |
<ul> | |
<li>If a method can be static, declare it static. Speed improvement is by a factor of 4.</li> | |
<li>echo is faster than print.(<em>* compare with list from phplens by John Lim</em>)</li> | |
<li>Use echo’s multiple parameters instead of string concatenation.</li> | |
<li>Set the maxvalue for your for-loops before and not in the loop.</li> | |
<li>Unset your variables to free memory, especially large arrays.</li> | |
<li>Avoid magic like __get, __set, __autoload</li> | |
<li>require_once() is expensive</li> | |
<li>Use full paths in includes and requires, less time spent on resolving the OS paths.</li> | |
<li>If you need to find out the time when the script started executing, $_SERVER[’REQUEST_TIME’] is preferred to time()</li> | |
<li>See if you can use strncasecmp, strpbrk and stripos instead of regex</li> | |
<li>str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4</li> | |
<li>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.</li> | |
<li>It’s better to use select statements than multi if, else if, statements.</li> | |
<li>Error suppression with @ is very slow.</li> | |
<li>Turn on apache’s mod_deflate</li> | |
<li>Close your database connections when you’re done with them</li> | |
<li>$row[’id’] is 7 times faster than $row[id]</li> | |
<li>Error messages are expensive</li> | |
<li>Do not use functions inside of for loop, such as for ($x=0; $x < count($array); $x) The count() function gets called each time.</li> | |
<li>Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in a function.</li> | |
<li>Incrementing a global variable is 2 times slow than a local var.</li> | |
<li>Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable.</li> | |
<li>Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.</li> | |
<li>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.</li> | |
<li>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.</li> | |
<li>Methods in derived classes run faster than ones defined in the base class.</li> | |
<li>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.</li> | |
<li>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.</li> | |
<li>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.</li> | |
<li>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.</li> | |
<li>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.</li> | |
<li>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</li> | |
<li>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.<br> | |
<strong>Ex.</strong><p></p> | |
<div id="highlighter_367921" class="syntaxhighlighter "><div class="bar"><div class="toolbar"><a class="item viewSource" style="width: 16px; height: 16px;" title="view source" href="#viewSource">view source</a><a class="item printSource" style="width: 16px; height: 16px;" title="print" href="#printSource">print</a><a class="item about" style="width: 16px; height: 16px;" title="?" href="#about">?</a></div></div><div class="lines"><div class="line alt1"><code class="number">1.</code><span class="content"><span class="block" style="margin-left: 0px !important;"><code class="keyword">if</code> <code class="plain">(</code><code class="functions">strlen</code><code class="plain">(</code><code class="variable">$foo</code><code class="plain">) < 5) { </code><code class="functions">echo</code> <code class="string">"Foo is too short"</code><code class="plain">; }</code></span></span></div></div></div> | |
<p><strong>vs.</strong></p> | |
<div id="highlighter_148121" class="syntaxhighlighter "><div class="bar"><div class="toolbar"><a class="item viewSource" style="width: 16px; height: 16px;" title="view source" href="#viewSource">view source</a><a class="item printSource" style="width: 16px; height: 16px;" title="print" href="#printSource">print</a><a class="item about" style="width: 16px; height: 16px;" title="?" href="#about">?</a></div></div><div class="lines"><div class="line alt1"><code class="number">1.</code><span class="content"><span class="block" style="margin-left: 0px !important;"><code class="keyword">if</code> <code class="plain">(!isset(</code><code class="variable">$foo</code><code class="plain">{5})) { </code><code class="functions">echo</code> <code class="string">"Foo is too short"</code><code class="plain">; }</code></span></span></div></div></div> | |
<p>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.</p></li> | |
<li>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.</li> | |
<li>Not everything has to be OOP, often it is too much overhead, each method and object call consumes a lot of memory.</li> | |
<li>Do not implement every data structure as a class, arrays are useful, too</li> | |
<li>Don’t split methods too much, think, which code you will really re-use</li> | |
<li>You can always split the code of a method later, when needed</li> | |
<li>Make use of the countless predefined functions</li> | |
<li>If you have very time consuming functions in your code, consider writing them as C extensions</li> | |
<li>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</li> | |
<li>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%</li> | |
<li><a rel="external,nofollow" href="http://phplens.com/lens/php-book/optimizing-debugging-php.php" target="_blank">Excellent Article</a> about optimizing php by John Lim</li> | |
</ul> | |
<p>As Reihold Webber pointed to a post from <a rel="external,nofollow" href="http://phplens.com/lens/php-book/optimizing-debugging-php.php" target="_blank">John Lim</a> (found this article copied without state the source <a rel="external,nofollow" href="http://www.whenpenguinsattack.com/2006/07/21/optimizing-object-oriented-php" target="_blank">here</a>), then i investigate further and truly that is an excellent best practice tutorial for optimizing the php code performance, covered almost all aspects from low level webserver configuration, PHP configuration, coding styling, and performace comparisson as well.</p> | |
<p>Another good practice for better php performance as written in <a rel="external,nofollow" href="http://www.cluesheet.com/" target="_blank">cluesheet.com</a> are:</p> | |
<ul> | |
<li>Do use single quotes over double quotes.</li> | |
<li>Do use switch over lots of if statements</li> | |
<li>Do avoid testing loop conditionals with function tests every iteration eg. for($i=0;i<=count($x);$i++){…</li> | |
<li>Do use foreach for looping collections/arrays. PHP4 items are byval, greater than PHP5 items are byref</li> | |
<li>Do consider using the Singleton Method when creating complex PHP classes.</li> | |
<li>Do use POST over GET for all values that will wind up in the database for TCP/IP packet performance reasons.</li> | |
<li>Do use ctype_alnum,ctype_alpha and ctype_digit over regular expression to test form value types for performance reasons.</li> | |
<li>Do use full file paths in production environment over basename/fileexists/open_basedir to avoid performance hits for the filesystem having to hunt through the file path. Once determined, serialize and/or cache path values in a $_SETTINGS array. $_SETTINGS["cwd"]=cwd(./);</li> | |
<li>Do use require/include over require_once/include_once to ensure proper opcode caching.</li> | |
<li>Do use tmpfile or tempnam for creating temp files/filenames</li> | |
<li>Do use a proxy to access web services (XML or JSOM) on foreign domains using XMLHTTP to avoid cross-domain errors. eg. foo.com<–>XMLHTTP<–>bar.com</li> | |
<li>Do use error_reporting (E_ALL); during debug.</li> | |
<li>Do set Apache allowoverride to “none” to improve Apache performance in accessing files/directories.</li> | |
<li>Do use a fast fileserver for serving static content (thttpd). static.mydomain.com, dynamic.mydomain.com</li> | |
<li>Do serialize application settings like paths into an associative array and cache or serialize that array after first execution.</li> | |
<li>Do use PHP output control buffering for page caching of heavilty accessed pages</li> | |
<li>Do use PDO prepare over native db prepare for statements. mysql_attr_direct_query=>1</li> | |
<li>Do NOT use SQL wildcard select. eg. SELECT *</li> | |
<li>Do use database logic (queries, joins, views, procedures) over loopy PHP.</li> | |
<li>Do use shortcut syntax for SQL insers if not using PDO parameters parameters. eg. INSERT INTO MYTABLE (FIELD1,FIELD2) VALUES ((“x”,”y”),(“p”,”q”));</li> | |
</ul> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I don't know this list is written for which version of PHP but I had several tests in PHP 7.2 and 8.1 for comparing preg_replace & str_replace. The result was near but preg_replace was a little faster each time!