Benchmarking of PHP string manipulations
inspired by:
http://www.jaisenmathai.com/blog/2008/02/29/10-tips-to-make-your-php-application-scream-part-2-of-n/
written for:
conductr.com
Each operation is microtime(true)ed while 100,000 executions occur. Then compared with its alternative.
// this is slower
// if(intval($age) > 13)
// this is faster
// if((int)$age) > 13)
SLOWER: 0.04351806640625 s
FASTER: 0.018932104110718 s
RESULT: RIGHT by 0.024585962295532 s
// this is slower
// array_push($myArray, 'myValue');
// this is faster
// $myArray[] = 'myValue';
SLOWER: 0.063239812850952 s
FASTER: 0.032866954803467 s
RESULT: RIGHT by 0.030372858047485 s
// this is slower
// substr($string, 3, 1);
// this is faster
// $string[3];
SLOWER: 0.044908046722412 s
FASTER: 0.0076150894165039 s
RESULT: RIGHT by 0.037292957305908 s
// this is slower
// "Hello, my name is $name";
// this is faster
// 'Hello, my name is ' . $name;
// this is fastest (using comma instead of period)
// 'Hello, my name is ' , $name;
SLOWER: 0.0157790184021 s
FASTER: 0.014382123947144 s
FASTst: GIVES SYNTAX ERROR? s
RESULT: RIGHT by 0.0013968944549561 s
// this is slower
// preg_match('/^abcde/', $string);
// this is faster
// strncmp('abcde', $string, 5);
SLOWER: 0.08721399307251 s
FASTER: 0.045006990432739 s
RESULT: RIGHT by 0.042207002639771 s
// this is slower
// if(false || true)
// this is faster
// if(true || false)
SLOWER: 0.011602878570557 s
FASTER: 0.010727882385254 s
RESULT: RIGHT by 0.00087499618530273 s
// this is slower
// $var++
// this is faster
// ++$var
SLOWER: 0.011069059371948 s
FASTER: 0.011872053146362 s
RESULT: WRONG by -0.00080299377441406 s