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.
time required (shorter is better)
rank / method / description / code
resulting output
<?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 dogback to the PHP benchmark results
<?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 dogback to the PHP benchmark results
<?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 dogback to the PHP benchmark results