Question

What can I do to increase the performance/speed of my PHP scripts without installing software on my servers?

Was it helpful?

Solution

Profile. Profile. Profile. I'm not sure if there is anything out there for PHP, but it should be simple to write a little tool to insert profiling information in your code. You will want to profile function times and SQL query times.

So where you have a function:

function foo($stuff) {
    ...
    return ...;
}

I would change it to:

function foo($stuff) {
    trace_push_fn('foo');
    ...
    trace_pop_fn('foo');
    return ...;
}

(This is one of those cases where multiple returns in a function become a hinderance.)

And SQL:

function bar($stuff) {
    trace_push_fn('bar');

    $query = ...;
    trace_push_sql($query);
    mysql_query($query);
    trace_pop_sql($query);

    trace_pop_fn('bar');
    return ...;
}

In the end, you can generate a full trace of the program execution and use all sorts of techniques to identify your bottlenecks.

OTHER TIPS

One reasonable technique that can easily be pulled off the shelf is caching. A vast amount of time tends to go into generating resources for clients that are common between requests (and even across clients); eliminating this runtime work can lead to dramatic speed increases. You can dump the generated resource (or resource fragment) into a file outside the web tree, and then read it back in when needed. Obviously, some profiling will be needed to ensure this is actually faster than regeneration - forcing the web server back to disk regularly can be detrimental, so the resource really does need to have heavy reuse.

You might also be surprised how much time is spent inside badly written database queries; time common generated queries and see if they can be rewritten. The amount of time spent executing actual PHP code is generally pretty limited, unless you're using some sub-optimal algorithms.

Neither of these are limited to PHP, though some of the PHP "magicy" approaches/functions can over-protect one from thinking about these concerns. For example, I recently updated a script that was using array_search to use a binary search over a sorted array, and gained the expected exponential speedup.

Really consider using XDebug profiler: it helps with checking how much a certain function is being executed against what you would have expected.

I try to decrease instructions while improving code readability by replacing logic with array-lookups when appropriate. It's what Jeff Atwood wrote in [The Best Code is No Code At All][1].

  • Also, avoid loops inside another loop, and nested if/else statements.
  • Short functions. Sometimes a lot of code does not need to be executed when the result-value is already known.
  • Unnecessary testing:

    if (count($array) === 0) return;

    can also be written as:

    if (! $array) return;

    Another function-call eliminated!

    [1]: http://www.codinghorror.com/blog/archives/000878.html"The Best Code is No Code At All"

You can optimized the code with two basic things:

Optimizing PHP associated library and server

Go through https://www.digitalocean.com/community/articles/how-to-optimize-apache-web-server-performance Or

You can use profiling tool like xhprof to view what part of your code can by optimized and here is the link to follow: http://michaelsanford.com/compiling-xhprof-for-php-5-4/

Optimizing your code using code profiler and code analyzer

You need to install Netbeans in order to use this plugin. Here are the steps you need to follow:

1) Open NetBeans then select option from menu bar Tools > Plugin. Then search plug-in name "phpcsmd" in the available plug-in tab and install it from there.

2) Now open the terminal and be there as the super user by typing command "sudo su".

3) Install PEAR library (if it is not installed) into your system by running following commands into your terminal

a) wget http://pear.php.net/go-pear.phar
b) php go-pear.phar

As we need this for the installation of further addons.

4) Then run the command

"pear config-set auto_discover 1"

This will be used to set auto discover the path "true" for the required plug-ins. So they get install to the desired location automatically.

5) Then run below command to install PHP code sniffer.

"pear install --alldeps pear/PHP_CodeSniffer"

6) Now to install the PHP Mess Detector by running following command

"pear install --alldeps phpmd/PHP_PMD"

If you get the error like "invalid package name/package file "phpmd/PHP_PMD"" while installing this module. You need to use this "pear channel-discover pear.phpmd.org" command to get rid of this error. After this command you can run the above command again to install Mess detector.

7) Now to install the PHP Depend by running following command

"pear install --alldeps pdepend/PHP_Depend"

8) Now install the PHP Copy Paste Detector by running following command

"pear install --alldeps phpunit/phpcpd"

9) Then run the command

"pear config-set auto_discover 0"

This will be used to set auto discover path "false".

10) Then open net beans and follow the path Tools>Options>PHP>PHPCSMD

There is no magic solution, and attempting to provide generic solutions could well just be a waste of time.

Where are your bottlenecks? For example are your scripts processor/database/memory intensive?

Have you performed any profiling?

including files is slow, and requiring them is even slower. If you use __autoload for including every class then that will add up. for example.

I'm always a bit wary of trying to be too clever in terms of code optimisation, if it sacrifices code clairty. If you need to make code obscure to make it fast, would it not be cheaper to upgrade hardwear instead of wasting your time trying to tweak code? Processor cycles are cheaper than programmer cycles, after all.

The ones I can think of...

  • Loop invariants are always a good one to watch.

  • Write E_STRICT and E_NOTICE compliant code, particularly if you are logging errors.

  • Avoid the @ operator.

  • Absolute paths for requires and includes.

  • Use strpos, str_replace etc. instead of regular expressions whenever possible.

Then there's a bunch of other methods that might work, but probably wont give you much benefit.

Whenever I look at performance problems, I think the best thing to do is time how long your pages take to run, and then look at the slowest ones. When you get these real metrics, you can often improve performance on the slowest ones by orders of magnitude, either by fixing a slow SQL query or perhaps tightening up the code a bit.

This of course requires no new hardware or special software, just a critical eye on the existing code.

That said, this will only work for so long... if you really are getting enough traffic to hit the limits of your hardware, and/or there is some code that is just inherently slow and really required, you will have to look at other possibilities.

I'm responsible for a large reporting system and we track the slowest reports kind of like that. I fire a unique key into the db when the report starts and then when it finishes I can determine how long it took. I'm using the database because that way I can detect when pages timeout (which happens a lot more than I'd like)

Follow some of the other advice first like profiling and making good resource allocation decisions, e.g. caching.

Also, take into account the performance of outside resources like your database. In MySQL you can check the slow query log for example. In addition make sure you didn't design your database an forget about it. Optimizing your queries (again for MySQL) against real data can pay of big.

Rasmus Lerdorf gave some good tips in his recent presentation "Simple is Hard" at FrOSCon '08. If you are using a bytecode cache (and you really should be using one), include path misses hurt a lot, so optimize your require/require_once.

You can use profiling tool like xhprof to view what part of your code can by optimized !

1) Use latest version of PHP

The core team is working hard on improving the performance of PHP in every version.

2) Use a bytecode cache

Since PHP 5.5 a bytecode cache has been added to PHP named OPcache. Using OPcache can make a huge difference especially since PHP 7. It receives improvements in every PHP version and might even get a JIT implementation in the future.

3) Profiling

While developing profiling gives you great insight what exactly is happening. This helps a lot finding bottlenecks in your code.

One of the most used tools is XHProf but is not officially supported anymore and has issues with PHP >= 7. An alternative when you want to profile PHP >= 7 is Tideways which is a fork of XHProf.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top