PHP字元分割explode,split,preg_split效能比較
三個函數都是用來對字串進行分割,下面分幾個實驗來比較之間的效能。
1. explode與split比較
都用字元進行分割,執行10次
代碼:
for($num=0;$num<9;$num++){ $stime=microtime(); for($i=0;$i<10000;$i++) { explode(',','hello,world'); } $etime=microtime(); printf("explode takes %f \n",$etime-$stime);}for($num=0;$num<9;$num++){ $stime=microtime(); for($i=0;$i<10000;$i++) { split(',','hello,world'); } $etime=microtime(); printf("split takes %f \n",$etime-$stime);}
結果:
explode takes 0.009193
explode takes 0.007066
explode takes 0.007623
explode takes 0.005829
explode takes 0.005497
explode takes 0.005734
explode takes 0.005502
explode takes 0.005515
explode takes 0.005524
split takes 0.008976
split takes 0.008971
split takes 0.009030
split takes 0.009173
split takes 0.009913
split takes 0.012656
split takes 0.012153
split takes 0.009161
split takes 0.008948
結論:都用字元進行分割的情況下,explode效能優於split
split用正則進行分割:
代碼:
for($num=0;$num<9;$num++){ $stime=microtime(); for($i=0;$i<10000;$i++) { explode(',','hello,world'); } $etime=microtime(); printf("explode takes %f \n",$etime-$stime);}for($num=0;$num<9;$num++){ $stime=microtime(); for($i=0;$i<10000;$i++) { split('/,/','hello,world'); } $etime=microtime(); printf("split takes %f \n",$etime-$stime);}
結果:
explode takes 0.005649
explode takes 0.005719
explode takes 0.005792
explode takes 0.005975
explode takes 0.005723
explode takes 0.005812
explode takes 0.005860
explode takes 0.005756
explode takes 0.005835
split takes 0.005158
split takes 0.005170
split takes 0.005440
split takes 0.005402
split takes 0.005272
split takes 0.005434
split takes 0.006389
split takes 0.005414
split takes 0.005510
結論:在split使用正則分割的情況下,兩者效能不相上下
2. split與preg_split比較
代碼:
for($num=0;$num<9;$num++){ $stime=microtime(); for($i=0;$i<10000;$i++) { split('/,/','hello,world'); } $etime=microtime(); printf("split takes %f \n",$etime-$stime);}for($num=0;$num<9;$num++){ $stime=microtime(); for($i=0;$i<10000;$i++) { preg_split("/,/","hello,world"); } $etime=microtime(); printf("preg_split takes %f \n",$etime-$stime);}
結果:
split takes 0.005381
split takes 0.005568
split takes 0.005107
split takes 0.005097
split takes 0.005444
split takes 0.005538
split takes 0.005095
split takes 0.005112
split takes 0.005087
preg_split takes 0.009364
preg_split takes 0.009568
preg_split takes 0.009037
preg_split takes 0.008957
preg_split takes 0.009021
preg_split takes 0.009656
preg_split takes 0.009038
preg_split takes 0.008962
preg_split takes 0.009412
結論:split效能優於preg_split