Wednesday, 26 June 2019

Best practice to optimize PHP code performances

Category : PHP Script
  • If a method can be static, declare it static. Speed improvement is by a factor of 4.
    this is for variable in class. e.g : static public $connection;
  • echo is faster than print.
  • echo 'callrid' is faster than echo "callrid"
  • Set the maxvalue for your for-loops before and not in the loop. such as for ($x=0; $x < count($array); $x) The count() function gets called each time better use :
    $max_value = count($array);
    for ($i=0;$i<$max_value;$i++) {
    echo $i;
    }
  • Unset your variables to free memory, especially large arrays.
    unset($array_var);
  • Use full paths in includes and requires, less time spent on resolving the OS paths.
    <img src="../../img/example.gif"> is better than <img src="http://www.example.com/img/example.gif">
  • 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 many condition, It’s better to use select statements (switch case) than multi if, else if, statements
  • Error suppression with @ is very slow
  • $row[’id’] is 7 times faster than $row[id]
  • 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.
    $i = 0; $i++ is faster than just $i++;
  • 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.
    echo "a","b" is faster than echo "a"."b";
  • echo "a $b" is faster than echo 'a'.$b;
  • 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
    <? echo "<img src='path'>" ?> is faster if we use static HMTL just : <img src="path">

  • Use echo’s multiple parameters instead of string concatenation.
  • 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]
  • 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.
    1. if (strlen($foo) < 5) { echo "Foo is too short"; } 
    if (strlen($foo) < 5) { echo "Foo is too short"; }

    vs.

    1. if (!isset($foo{5})) { echo "Foo is too short"; } 
    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.
  • Do not implement every data structure as a class, arrays are useful, too
  • Do NOT use SQL wildcard select. eg. SELECT * FROM table
  • Do use database logic (queries, joins, views, procedures) over loopy PHP.
  • Do use shortcut syntax for SQL insers if not using PDO parameters parameters. eg. INSERT INTO table (FIELD1,FIELD2) VALUES ((”x”,”y”),(”p”,”q”));


Like this articles? share it with Share With FacebookFacebook
<< Back
3 Comment | 2775 hits | Posted by Callrid at 2008-11-20 10:16:43

Related Read

Add Comment
Name :
Web :
Comment :

Code :
 

Other Source
A Practical Guide On Complete Multivitamins
Many of us have a hard time deciding what the best multivitamin is for us. This is completely confusing and difficult especially when there are so many bottles to scan in the various aisles of the...

High Blood Pressure
The nutritional benefits of low-fat dairy products are well known for ages. The latest studies show that the ingredients of dairy products - some combination of milk proteins are effective and...

Welcome To Mimicwatch.com - Quality Luxury Replica Vacheron Constantin Watches At Affordable Price
When entering our online store at Mimicwatch.com, you are given an unique opportunity to choose among a wide selection of famous Replica Watches and Replica handbags such as Replica Vacheron...

Ebook Marketing Tips
A great way to have a product to sell on the Internet is an e-book which almost anyone can create. There is no longer any need for delaying with the simple process detailed below. If you are afraid...

Tactical Asset Marketing
Asset Management Different Asset Allocation Strategies Asset marketing is the process of dividing a portfolio into major asset categories such as cash, stocks, real estate, or...

Shout Box
2019-04-10 21:32:43 
StivenSortPat
http://newseastwest.com/was-mukesh-ambanis-son-akash-ambani-driving-the-sports-car-that-killed-two-people/comment-page-1/#comment-338201
2019-02-26 22:20:45 
Playavmk

2016-11-24 08:56:05 
Pembicara Internet M
Website yagn bagus
2016-11-24 08:40:45 
Produsen Mukena
Good Website
2016-04-05 20:44:45 
Belanja Alat ukur
Belanja Alat ukur dan Thermal Camera Hanya di dutapersada.co.id

Site Partners


Search Articles

Web Statistic
No Visitor :
3270090
Today Visitor :
233
Online Visitor :
1
what is my ip address? Page Rank Checker

< Jun 2019 >
SMTWTFS
      1
2345678
9101112131415
16171819202122
23242526272829
30

Increase Page Rank

Last Modified 08-November-2011, 23:21:04 pm
callrid.com Created 2006-2012 by Anton Ongsono
All rights reserved