background image

PHP 入门:

strtr, str_replace 和 preg_replace 三个函数的效率

以下是对

strtr

str_replace

preg_replace 三个函数的效率问题的说明与比较区分

之前已经分析过

strtr

的源码了,现在就比较

strtr

str_replace

preg_replace 的效率:

代码如下

:

 

$str

 = 

'1111111100000000000000000000000000000001110000010001000100000100100000100100000
10100000010
'; 

$str

 = 

str_repeat

(

$str

, 1); 

$pattern1

 = 

array

('12345'=>'', '67891'=>''); 

$pattern2

 = 

array

('a'=>'', '1234567890'=>''); 

$pattern3

 = '/12345|67891/'; 

$pattern4

 = '/a|1234567890/'; 

$pattern5

 = 

array

('12345', '67891'); 

$pattern6

 = 

array

('a', '1234567890'); 

$t

 = microtime(true); 

for

(

$i

=0; 

$i

<10000; 

$i

++) 

{

strtr

(

$str

$pattern1

); 

echo

 microtime(true)-

$t

, "/n"; 

//0.21915886878967 0.47268319129944 

$t

 = microtime(true); 

for

(

$i

=0; 

$i

<10000; 

$i

++) 

{

strtr

(

$str

$pattern2

); 

echo

 microtime(true)-

$t

, "/n"; 

//0.4768660068512 2.7257590293884 

$t

 = microtime(true); 

for

(

$i

=0; 

$i

<10000; 

$i

++) 

{
preg_replace(

$pattern3

, '', 

$str

); 

echo

 microtime(true)-

$t

, "/n"; 

//0.30504012107849 1.0864448547363 

$t

 = microtime(true); 

for

(

$i

=0; 

$i

<10000; 

$i

++) 

{