Hello Everyone Today in this blog you are going to learn the PHP code optimization techniques.
Code optimization in PHP is a program transformation technique, which tries to improve the code by making it consume fewer resources (i.e. CPU, Memory) and deliver high speed.
Why code optimization in PHP is needed ???
-
- To improve intermediate code
- Executes Faster
- Shorter code
- Better target code
- Complexity: Time, Space & Cost
- Efficient memory usage
- Better performance.
Now we see 50 PHP code optimization techniques with the help of which we can run our codes faster.
- echo is faster than print.
- Use echo’s multiple parameters instead of string concatenation.
- If a method can be static, declare it static. Speed improvement is by a factor of 4.
- Use full paths in includes and requires, less time spent on resolving the OS paths.
- require_once() is expensive.
- If you need to find out the time when the script started executing, $_SERVER[’REQUEST_TIME’] is preferred to time().
- Unset your variables to free memory, especially large arrays.
- Set the max value for your for-loops before and not in the loop.
- 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 replaces arguments.
- Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.
- See if you can use strncasecmp, strpbrk and stripos instead of regex.
- Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable.
- Methods in derived classes run faster than ones defined in the base class.
- 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.
- Error messages are expensive
- Close your database connections when you’re done with them
- 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.
- 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%.
- Not everything has to be OOP, often it is too much overhead, each method and object call consumes a lot of memory.
- Do use single quotes over double quotes.
You May Also Like:
- Do not use functions inside of for loop, such as for ($x=0; $x < count($array); $x) The count() function gets called each time.
- $row[’id’] is 7 times faster than $row[‘id’].
- 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.
- 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.
- 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
- 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.
- 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.
- 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.
- Do use switch over lots of if statements.
- Do avoid testing loop conditionals with function tests every iteration eg. for($i=0;i<=count($x);$i++){…
- Do use foreach for looping collections/arrays. PHP4 items are byval, greater than PHP5 items are byref
- Do consider using the Singleton Method when creating complex PHP classes.
- Do use POST over GET for all values that will wind up in the database for TCP/IP packet performance reasons.
- Do use ctype_alnum,ctype_alpha and ctype_digit over regular expression to test form value types for performance reasons.
- Do use require/include over require_once/include_once to ensure proper opcode caching.
- Do use tmpfile or tempname for creating temp files/filenames
- Do use error_reporting (E_ALL); during debug.
- Do serialize application settings like paths into an associative array and cache or serialize that array after first execution.
- Do use PHP output control buffering for page caching of heavilty accessed pages.
- Do use PDO prepare over native db prepare for statements. mysql_attr_direct_query=>1
- Do NOT use SQL wildcard select. eg. SELECT *
- Do use database logic (queries, joins, views, procedures) over loopy PHP.
- Do use shortcut syntax for SQL insert if not using PDO parameters. eg. INSERT INTO TABLE (FIELD1, FIELD2) VALUES ((“x”,”y”),(“p”,”q”));