Thursday, March 15, 2012

PHP - Coding Tips #1

In PHP there are so many ways to perform the same task. Normally developers are using the way which is most comfortable for them or which they are more aware of.
  1. echo is more faster than print. Both functions are used for the same thing but echo is the language construct which return nothing, which print will return 0 or 1 based on success or failure.
  2. include_once is more costly than include statement. Because it have to search for class definition you are trying to include is already included or not?
  3. Always use single quotes for long strings instead of double quotes. Because in double quotes it will search for php variable to evaluate them. So in this case, echo ‘This is long string’ . $name is faster then echo “This is long string $name”. But from above both echo ‘This is long string’ , $name, is faster because it does not require any string manipulation.
  4. Don’t use for( $i=0; $i < count ($ names );$i++){…} instead of this use $size = count($names); for($i=0; $ i<$ size;$i++){…}. The first method will call count function on each iteration of for loop, while in second iteration count function is being called only once.
  5. If you can declare a method as static then let it be, because its 33% more faster than member functions.
  6. If you can solve your problem without using regular expression then don’t use it. Regular expression are slower then their php counterparts. For example use str_replace instead of preg_replace.
  7. Try to minimize relative paths for files inclusion. For relative path inclusion it will search for default include path then current directory then so on. So file search in that case may take more time. Better practice is to declare the constant called WEB_ROOT which defines the root.
  8. Identical operator (===) is faster than (==) operator as identical operator will include type checking also. So If( 1 == ’1′) will return true, If( 0 == ”) will return true while if you use identical operator both this conditions If( 1 === ’1′) and If(0 === ”)  will return false. So it is recommended to use identical operator when you are going to use some boolean variables for deciding the flow/control of your application.
  9. Don’t use short tags and try to using , It can create a problem for you if you are going to deploy your application on another server.
  10. Don’t use or relay on register_globals or magic quotes and read and configure your php.ini settings carefully.
Post a Comment

Popular Posts