SlideShare a Scribd company logo
1 of 13
05/19/12   php optimization   1
 There are many ways to improve the way you write your PHP
       code.
        And we can easily increase the efficiency of our code just by
       putting in some effort during development.
        However, there might be some unknown information that you
       might not aware in PHP that can help improve your code.

              In php optimization concepts looks more efficient than
             other things.

             They are followings in next slides,




05/19/12                      php optimization                    2
ECHO VS PRINT:
        Echo is better.
        But how much better?
        Its around 12%-20% faster using echo compare to print
       when there is no $ symbol in the printing string.
        And around 40-80% faster if there is an $ symbol used in a
       printing string!

           SINGLE VS DOUBLE QUOTES:
                Single(’) quote is faster than double(”) quote.

                Why? Because PHP will scan through double quote
               strings for any PHP variables (additional operation).

                So unless you have a $var inside the string use single
                 quotes.
05/19/12                      php optimization                     3
Ex:1
      $var = 'I have text';
      $var2 = "I have text"; // We dont have vars so single would be good;
      $var3 = "I have $var"; // In this case the double quotes is necessary

       LOOP:
            Loop is considered as efficiency killer if you have many
           nested loop (means loop in a loop) as one loop will required to
           run ‘n’ times
            If you have 1 nested loop, this means your program will have
           to run n2 times.

                  Using a for loop is better than foreach and while loop
                 if the maximum loop is pre-calculated outside the for
                 loop!

05/19/12                          php optimization                       4
Ex:2

           // For each loop the count function is being called.
            for($i =0; $i < count($array);$i++)
           { echo 'This is bad'; }

            #Better than foreach and while loop
            $total = (int)count($array);
           for($i =0; $i < $total;$i++)
           { echo 'This better, max loop was pre-calculated'; }

                  DOT VS COMMAS CONCATENATION:
                  $a = '10 PHP programming ';
                   $b = 'Improvement Tips';
                  #10 PHP Programming Improvement Tips
                   echo $a.$b;
05/19/12                         php optimization                 5
The other way is:
            $a = 'PHP ';
            $b = 'Tips';
             echo $a,$b;
            Tests show that dot is more preferable if there are no
           variables or $ symbol involved which is around 200% faster.
            On the other hand, commas will help to increase around
           20%-35% efficiency when dealing with $ symbols.

                 PRE INCREMENT VS POST INCREMENT:
                   In PHP, it seems like pre increment is better than the
                  other ways of performing an increment.
                   Its around 10% better than post increment? The
                  reason? Some said that post increment made certain
                  copy unlike pre increment.
05/19/12                         php optimization                     6
EX:3
              $i++;
              ++$i;
               $i+=1;
               $i = $i + 1;

           EXPLODE VS PREG_SPLIT:
            To split a string the usual way is to use explode because it
           support even on PHP4.0. The answer in term of efficiency is
           explode.
            Split supports regular express and this makes it quite the
           same comparison between str_replace and preg_replace,
           anything that have regular expression support will usually be a
           bit more slower than those that doesn’t support it.
                      It took around 20.563% faster using explode in
                     PHP.

05/19/12                          php optimization                      7
WHEN CHECKING THE LENGTH OF STRINGS:

             Use isset where possible in replace of strlen.


                        if (!isset($foo{5}))
                        { echo "Foo is too short"; }
                        //is faster than
                         if (strlen($foo) < 5)
                        { echo "Foo is too short"; }




05/19/12                          php optimization            8
VARIABLES AND FUNCTIONS
             There are some handy things you can do with variables
            and functions in php to help optimize your script.
             Unset or null your variables to free memory, especially
            large arrays.
            Use require() instead of require_once() where possible.
             Use absolute paths in includes and requires. It means less
            time is spent on resolving the OS paths.
                   include('/var/www/html/your_app/test.php');
                   //is faster than
                    include('test.php');

                  require() and include() are identical in every way
                 except require halts if the file is missing. Performance
                 wise there is very little difference.
05/19/12                         php optimization                     9
“else if” statements are faster than “switch/case”
           statements.

           PHP OPTIMISATION TIPS REVISITED:
               Avoid magic like __get, __set, __autoload.

               Since PHP5, the time of when the script started executing can be
                found in $_SERVER[’REQUEST_TIME’], use this instead of time()
                or microtime().
                   When parsing with XML in PHP try xml2array, which makes use
                  of the PHP XML functions, for HTML you can try PHP’s
                  DOM document or DOM XML in PHP4.

                    str_replace is faster than preg_replace, str_replace is best
                   overall, however strtr is sometimes quicker with larger strings.
                   Using array() inside str_replace is usually quicker than multiple
                   str_replace. [
05/19/12                             php optimization                            10
 Close your database connections when you’re done with them.

            $row[’id’] is 7 times faster than $row[id], because if you don’t supply
           quotes it has to guess which index you meant, assuming you didn’t mean a
           constant.

              Use <?php … ?> tags when declaring PHP as all other styles are
             depreciated, including short tags.

                  When using header(‘Location: ‘.$url); remember to follow it with a
                 die(); as the script continues to run even though the location has
                 changed or avoid using it all together where possible.

                    Incrementing a local variable in an OOP method is the fastest.
                   Nearly the same as calling a local variable in a function and
                   incrementing a global variable is 2 times slow than a local
                   variable.


05/19/12                              php optimization                            11
 Methods in derived classes run faster than ones defined in the base class.

            If you need to find out the time when the script started executing,
           $_SERVER['REQUEST_TIME'] is preferred to time()

            Incrementing an object property (eg. $this->prop++) is 3 times
           slower than a local variable.
                 true is faster than TRUE:
                 This is because when looking for constants PHP does a
                hash lookup for name as is.
                 And since names are always stored lowercased, by
                using them you avoid 2 hash lookups.
                Furthermore, by using 1 and 0 instead of TRUE and
                FALSE, can be considerably faster.
05/19/12                             php optimization                              12
select vs. multi if and else if statements:
             It’s better to use select statements than multi if, else if statements.




05/19/12                              php optimization                             13

More Related Content

What's hot (20)

Basic of PHP
Basic of PHPBasic of PHP
Basic of PHP
 
Php mysql training-in-mumbai
Php mysql training-in-mumbaiPhp mysql training-in-mumbai
Php mysql training-in-mumbai
 
Php(report)
Php(report)Php(report)
Php(report)
 
Dynamic website
Dynamic websiteDynamic website
Dynamic website
 
Php string function
Php string function Php string function
Php string function
 
Better rspec 進擊的 RSpec
Better rspec 進擊的 RSpecBetter rspec 進擊的 RSpec
Better rspec 進擊的 RSpec
 
Php tutorial(w3schools)
Php tutorial(w3schools)Php tutorial(w3schools)
Php tutorial(w3schools)
 
PHP Loops and PHP Forms
PHP  Loops and PHP FormsPHP  Loops and PHP Forms
PHP Loops and PHP Forms
 
Lesson 2 php data types
Lesson 2   php data typesLesson 2   php data types
Lesson 2 php data types
 
Php introduction
Php introductionPhp introduction
Php introduction
 
PHP Interview Questions-ppt
PHP Interview Questions-pptPHP Interview Questions-ppt
PHP Interview Questions-ppt
 
PHP Basic & Variables
PHP Basic & VariablesPHP Basic & Variables
PHP Basic & Variables
 
Phpをいじり倒す10の方法
Phpをいじり倒す10の方法Phpをいじり倒す10の方法
Phpをいじり倒す10の方法
 
Winter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHPWinter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHP
 
Php Lecture Notes
Php Lecture NotesPhp Lecture Notes
Php Lecture Notes
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Php Loop
Php LoopPhp Loop
Php Loop
 
PHP
PHPPHP
PHP
 
PHP slides
PHP slidesPHP slides
PHP slides
 
PHP
PHPPHP
PHP
 

Viewers also liked

Viewers also liked (7)

Carmelspain
CarmelspainCarmelspain
Carmelspain
 
Mathematics 2
Mathematics 2Mathematics 2
Mathematics 2
 
Search for the truth
Search for the truthSearch for the truth
Search for the truth
 
Php security
Php securityPhp security
Php security
 
Opposites
OppositesOpposites
Opposites
 
La mañana en el Blog Day
La mañana en el Blog DayLa mañana en el Blog Day
La mañana en el Blog Day
 
Webdesignanddevelopment
WebdesignanddevelopmentWebdesignanddevelopment
Webdesignanddevelopment
 

Similar to Pp

Winter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHPWinter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHPtutorialsruby
 
PHP Basics Ebook
PHP Basics EbookPHP Basics Ebook
PHP Basics EbookSwanand Pol
 
In-Depth Guide On WordPress Coding Standards For PHP & HTML
In-Depth Guide On WordPress Coding Standards For PHP & HTMLIn-Depth Guide On WordPress Coding Standards For PHP & HTML
In-Depth Guide On WordPress Coding Standards For PHP & HTMLeSparkBiz
 
Learn PHP Basics
Learn PHP Basics Learn PHP Basics
Learn PHP Basics McSoftsis
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Muhamad Al Imran
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Muhamad Al Imran
 
FYBSC IT Web Programming Unit IV PHP and MySQL
FYBSC IT Web Programming Unit IV  PHP and MySQLFYBSC IT Web Programming Unit IV  PHP and MySQL
FYBSC IT Web Programming Unit IV PHP and MySQLArti Parab Academics
 
An overview of upcoming features and improvements of PHP7
An overview of upcoming features and improvements of PHP7An overview of upcoming features and improvements of PHP7
An overview of upcoming features and improvements of PHP7Cloudways
 
Upstate CSCI 450 PHP Chapters 5, 12, 13
Upstate CSCI 450 PHP Chapters 5, 12, 13Upstate CSCI 450 PHP Chapters 5, 12, 13
Upstate CSCI 450 PHP Chapters 5, 12, 13DanWooster1
 

Similar to Pp (20)

Start using PHP 7
Start using PHP 7Start using PHP 7
Start using PHP 7
 
Winter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHPWinter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHP
 
PHP Basics Ebook
PHP Basics EbookPHP Basics Ebook
PHP Basics Ebook
 
phptutorial
phptutorialphptutorial
phptutorial
 
phptutorial
phptutorialphptutorial
phptutorial
 
In-Depth Guide On WordPress Coding Standards For PHP & HTML
In-Depth Guide On WordPress Coding Standards For PHP & HTMLIn-Depth Guide On WordPress Coding Standards For PHP & HTML
In-Depth Guide On WordPress Coding Standards For PHP & HTML
 
php basics
php basicsphp basics
php basics
 
Doc
DocDoc
Doc
 
Learn PHP Basics
Learn PHP Basics Learn PHP Basics
Learn PHP Basics
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
 
Php i basic chapter 3
Php i basic chapter 3Php i basic chapter 3
Php i basic chapter 3
 
FYBSC IT Web Programming Unit IV PHP and MySQL
FYBSC IT Web Programming Unit IV  PHP and MySQLFYBSC IT Web Programming Unit IV  PHP and MySQL
FYBSC IT Web Programming Unit IV PHP and MySQL
 
Learn php with PSK
Learn php with PSKLearn php with PSK
Learn php with PSK
 
An overview of upcoming features and improvements of PHP7
An overview of upcoming features and improvements of PHP7An overview of upcoming features and improvements of PHP7
An overview of upcoming features and improvements of PHP7
 
Unit 1
Unit 1Unit 1
Unit 1
 
Guidelines php 8 gig
Guidelines php 8 gigGuidelines php 8 gig
Guidelines php 8 gig
 
Upstate CSCI 450 PHP Chapters 5, 12, 13
Upstate CSCI 450 PHP Chapters 5, 12, 13Upstate CSCI 450 PHP Chapters 5, 12, 13
Upstate CSCI 450 PHP Chapters 5, 12, 13
 
Php optimization
Php optimizationPhp optimization
Php optimization
 
Php essentials
Php essentialsPhp essentials
Php essentials
 

Recently uploaded

Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 

Recently uploaded (20)

Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 

Pp

  • 1. 05/19/12 php optimization 1
  • 2.  There are many ways to improve the way you write your PHP code.  And we can easily increase the efficiency of our code just by putting in some effort during development.  However, there might be some unknown information that you might not aware in PHP that can help improve your code.  In php optimization concepts looks more efficient than other things. They are followings in next slides, 05/19/12 php optimization 2
  • 3. ECHO VS PRINT:  Echo is better.  But how much better?  Its around 12%-20% faster using echo compare to print when there is no $ symbol in the printing string.  And around 40-80% faster if there is an $ symbol used in a printing string! SINGLE VS DOUBLE QUOTES:  Single(’) quote is faster than double(”) quote.  Why? Because PHP will scan through double quote strings for any PHP variables (additional operation).  So unless you have a $var inside the string use single quotes. 05/19/12 php optimization 3
  • 4. Ex:1 $var = 'I have text'; $var2 = "I have text"; // We dont have vars so single would be good; $var3 = "I have $var"; // In this case the double quotes is necessary LOOP:  Loop is considered as efficiency killer if you have many nested loop (means loop in a loop) as one loop will required to run ‘n’ times  If you have 1 nested loop, this means your program will have to run n2 times.  Using a for loop is better than foreach and while loop if the maximum loop is pre-calculated outside the for loop! 05/19/12 php optimization 4
  • 5. Ex:2 // For each loop the count function is being called. for($i =0; $i < count($array);$i++) { echo 'This is bad'; } #Better than foreach and while loop $total = (int)count($array); for($i =0; $i < $total;$i++) { echo 'This better, max loop was pre-calculated'; } DOT VS COMMAS CONCATENATION: $a = '10 PHP programming '; $b = 'Improvement Tips'; #10 PHP Programming Improvement Tips echo $a.$b; 05/19/12 php optimization 5
  • 6. The other way is: $a = 'PHP '; $b = 'Tips'; echo $a,$b;  Tests show that dot is more preferable if there are no variables or $ symbol involved which is around 200% faster.  On the other hand, commas will help to increase around 20%-35% efficiency when dealing with $ symbols. PRE INCREMENT VS POST INCREMENT:  In PHP, it seems like pre increment is better than the other ways of performing an increment.  Its around 10% better than post increment? The reason? Some said that post increment made certain copy unlike pre increment. 05/19/12 php optimization 6
  • 7. EX:3 $i++; ++$i; $i+=1; $i = $i + 1; EXPLODE VS PREG_SPLIT:  To split a string the usual way is to use explode because it support even on PHP4.0. The answer in term of efficiency is explode.  Split supports regular express and this makes it quite the same comparison between str_replace and preg_replace, anything that have regular expression support will usually be a bit more slower than those that doesn’t support it.  It took around 20.563% faster using explode in PHP. 05/19/12 php optimization 7
  • 8. WHEN CHECKING THE LENGTH OF STRINGS: Use isset where possible in replace of strlen. if (!isset($foo{5})) { echo "Foo is too short"; } //is faster than if (strlen($foo) < 5) { echo "Foo is too short"; } 05/19/12 php optimization 8
  • 9. VARIABLES AND FUNCTIONS  There are some handy things you can do with variables and functions in php to help optimize your script.  Unset or null your variables to free memory, especially large arrays. Use require() instead of require_once() where possible.  Use absolute paths in includes and requires. It means less time is spent on resolving the OS paths. include('/var/www/html/your_app/test.php'); //is faster than include('test.php');  require() and include() are identical in every way except require halts if the file is missing. Performance wise there is very little difference. 05/19/12 php optimization 9
  • 10. “else if” statements are faster than “switch/case” statements. PHP OPTIMISATION TIPS REVISITED:  Avoid magic like __get, __set, __autoload.  Since PHP5, the time of when the script started executing can be found in $_SERVER[’REQUEST_TIME’], use this instead of time() or microtime().  When parsing with XML in PHP try xml2array, which makes use of the PHP XML functions, for HTML you can try PHP’s DOM document or DOM XML in PHP4.  str_replace is faster than preg_replace, str_replace is best overall, however strtr is sometimes quicker with larger strings. Using array() inside str_replace is usually quicker than multiple str_replace. [ 05/19/12 php optimization 10
  • 11.  Close your database connections when you’re done with them.  $row[’id’] is 7 times faster than $row[id], because if you don’t supply quotes it has to guess which index you meant, assuming you didn’t mean a constant.  Use <?php … ?> tags when declaring PHP as all other styles are depreciated, including short tags.  When using header(‘Location: ‘.$url); remember to follow it with a die(); as the script continues to run even though the location has changed or avoid using it all together where possible.  Incrementing a local variable in an OOP method is the fastest. Nearly the same as calling a local variable in a function and incrementing a global variable is 2 times slow than a local variable. 05/19/12 php optimization 11
  • 12.  Methods in derived classes run faster than ones defined in the base class.  If you need to find out the time when the script started executing, $_SERVER['REQUEST_TIME'] is preferred to time()  Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable. true is faster than TRUE:  This is because when looking for constants PHP does a hash lookup for name as is.  And since names are always stored lowercased, by using them you avoid 2 hash lookups. Furthermore, by using 1 and 0 instead of TRUE and FALSE, can be considerably faster. 05/19/12 php optimization 12
  • 13. select vs. multi if and else if statements:  It’s better to use select statements than multi if, else if statements. 05/19/12 php optimization 13

Editor's Notes

  1. 05/19/12 phpoptimization php optimization