PHP optimisation tips
Some tips for developers who want to make their code faster.
Benchmarking
Confirm any proposed performance measure by benchmarking it.
You can benchmark by timing, for example, in eval.php:
> $t = microtime(true); for( $i = 0; $i < 100000000; $i++ ) { md5('testing'); } print microtime(true)-$t;
13.321235179901
MediaWiki has benchmarking scripts in maintenance/benchmarks, including the generic utility benchmarkEval.php:
php benchmarkEval.php --code="md5('testing')" --inner=1000000 --count=100
Multiple timing runs will vary substantially. To minimise the impact of this:
- Use a large loop count to benchmark for a long time — at least 10 seconds.
- Avoid any other system activity while the benchmark runs. If you are using your laptop, kill your browser and anything else that might wake up periodically.
- Don't use a VM if there is any other activity on the same hardware.
- Avoid unnecessary I/O within the benchmark. For example, disable logging.
- Benchmark a small amount of code in a tight loop, so that the relative effect of the intervention will be larger.
Extremely accurate performance measurements can be done using hardware performance counters. On Linux you can use perf. On other operating systems you can use vtune -collect-with runsa [please confirm].
For example, running a benchmark under `perf stat -e instructions` will give a metric which is not affected by background activity on the same host. It tells you how much machine code is executed, which may be a decent model for cost depending on what you're measuring.