lixlpixel PHP Benchmarks

there are various common tasks in PHP which can be done in several ways.
this site aims to benchmark these different approaches to find the fastest solution to the problem.

sometimes there are builtin PHP functions which are (in the most cases) the fastest solutions.
but their options are limited so there might be some benchmarks which don't make sense to you at first.

replace various strings in a text

methods sorted by order executed

jump to method

time required (shorter is better)

methods sorted by performance

rank / method / description / code

resulting output

1. builtin strtr
  • 0.000451 seconds for 15 repeats
  • 0.3 x faster than preg replace



<?php

// ------- replace various strings in a text with builtin strtr

// -- the setup

$workdata '
the slow 
brown fox 
jumped over 
the lazy 
old bear'
;

$replacements['slow'] = 'quick';
$replacements['brown'] = 'black';
$replacements['fox'] = 'cat';
$replacements['lazy'] = 'sleeping';
$replacements['bear'] = 'dog';


// -- the code to test

$newworkdata strtr($workdata,$replacements);


?>
the quick 
black cat 
jumped over 
the sleeping 
old dog
back to the PHP benchmark results
2. string replace
  • 0.000488 seconds for 15 repeats
  • 0.2 x faster than preg replace
  • this code requires extra code



<?php

// ------- replace various strings in a text with string replace

// -- the setup

$workdata '
the slow 
brown fox 
jumped over 
the lazy 
old bear'
;

$replacements['slow'] = 'quick';
$replacements['brown'] = 'black';
$replacements['fox'] = 'cat';
$replacements['lazy'] = 'sleeping';
$replacements['bear'] = 'dog';


// -- extra code

$fromreplace = array();
$toreplace = array();
foreach(
$replacements as $from=>$to)
{
    
$fromreplace[] = $from;
    
$toreplace[] = $to;
}


// -- the code to test

$newworkdata str_replace($fromreplace,$toreplace,$workdata);


?>
the quick 
black cat 
jumped over 
the sleeping 
old dog
back to the PHP benchmark results
3. preg replace
  • 0.000578 seconds for 15 repeats
  • slowest method
  • this code requires extra code



<?php

// ------- replace various strings in a text with preg replace

// -- the setup

$workdata '
the slow 
brown fox 
jumped over 
the lazy 
old bear'
;

$replacements['slow'] = 'quick';
$replacements['brown'] = 'black';
$replacements['fox'] = 'cat';
$replacements['lazy'] = 'sleeping';
$replacements['bear'] = 'dog';


// -- extra code

$fromreplace = array();
$toreplace = array();
foreach(
$replacements as $from=>$to)
{
    
$fromreplace[] = '/'.$from.'/';
    
$toreplace[] = $to;
}


// -- the code to test

$newworkdata preg_replace($fromreplace,$toreplace,$workdata);


?>
the quick 
black cat 
jumped over 
the sleeping 
old dog
back to the PHP benchmark results