Back end optimization

Sang Le Thanh

GO1

http://cl.ly/Xoei

Normally case

  • Loop
  • Single vs Double Quotes
  • Pre increment vs Post increment
  • Absolute path vs Relative path
  • Echo vs Print
  • Dot vs Commas Concatenation
  • str_replace vs preg_replace
  • explode vs preg_split

Loop

for, foreach, while

#Worst than foreach and while loop
for($i =0; $i < count($array);$i++){
    echo 'This is bad, my friend';
}

#Better than foreach and while loop
$total = (int)count($array);
for($i =0; $i < $total;$i++){
    echo 'This is great, my friend';
}

Single vs Double Quotes

' is faster than "

Pre increment vs Post increment

$i++;
$++i
$i+=1;
$i = $i + 1;

Pre-increment where possible

 

Note that both the Zend Optimizer and IonCube PHP Accelerator will implement this optimisation for you.

Absolute Path VS Relative Path

Absolute path

Echo vs Print

Echo

Dot Vs Commas Concatenation

Dot

str_replace vs preg_replace

  • str_replace doesn’t run any complex expression unlike preg_replace => it faster
  • If you have to call str_replace 5 times compare to preg_replace, which will run faster? (str_replace, of course) Wrong! preg_replace runs 86.99% faster than 5 str_replace function call!

explode vs preg_split

explode faster

 

http://net-beta.net/ubench/index.php?t=preg5

Best practice

  • Cache resources
  • Lower io access
  • Using batch
  • Asynchonous
  • Search

Cache resource

  • APC for file
  • In shared_host, using database to cache
  • We can use APC, Memcached, Redis, MongoDB... to cache 
  • Cache using global and static for 1 request

RAM > Database > File

Lower io access

Normally this is optimize MySQL query

Ex: We have 3 table: node, comment, user.

Get 10 latest node with comments + user information

 

Usually: 1 query to get 10 node, then for each node run 1 query to get list of comments and 1 query to get user information, then for each comment to get user information

=> 100~200 query :(

 

We can resolve this with 3 query.

Using batch

Normally this is insert data to database or cache

 

Try to insert multiple rows in 1 time. Now MySQL, Memcached, MongoDB, Redis support it.

Asynchonous

We shouldn't let user wait a process take a long time to finish: Sending email, edit file, insert to database, data mining

 

But PHP isn't a thread => how can we solve it?

  • Running other program support thead to process it => need to learn other language
  • Using a bridge to a queue server like: RabbitMQ, ActiveMQ
  • Write each task to an php file and running via exec, system, pcntl_exec, passthru, popen...
  • cronjob
  • javascript ajax

Search

Don't use Database to search if you can

Reference

  • http://hungred.com/useful-information/php-micro-optimization-tips/
  • http://net-beta.net/ubench/
  • http://www.phpbench.com/
  • http://www.mdproductions.ca/guides/50-best-practices-to-optimize-php-code-performance

Q&A

Backend optimization

By Sang Lê Thanh

Backend optimization

  • 714