php - preg_replace VS str_replace (Which one is faster?)
one text
I 'm here after several tests for comparing speed of preg_replace & str_replace. Some documents claim that str_replace is 2x faster (because its simpler structure) but in my tests, each time preg_replace was faster a little!
The conditions :
PHP 8.1 & 7.2
Size of array : 8 millions rows
The average result :
preg_replace : 11.03159403801 s
str_replace : 11.209521055222 s
And This is my sample code :
<?php
//open file
$uri = 'src.csv';
//read csv
$content=file_get_contents($uri);
$lines = explode(PHP_EOL, $content);
//set timer
$start = microtime(true);
foreach ($lines as $line) {
//$array [] = run_preg_replace ($line);
$array [] = run_str_replace ($line);
}
//calc time
$end = microtime(true) - $start;
var_dump($end);
var_dump(count($array));
function run_preg_replace($str) { // remove new line and spaces
return trim(preg_replace('/\s+/', ' ', $str));
}
function run_str_replace($str) { // remove new lines
// Create an array with the values you want to replace
$searches = array("\r", "\n", "\r\n");
return trim(str_replace($searches,' ',$str));
}
?>
So it is a rumor or my code isn't good enough for this comparision?
Source