当前位置:Gxlcms > PHP教程 > PHP字符分割explode,split,preg_split性能比较

PHP字符分割explode,split,preg_split性能比较

时间:2021-07-01 10:21:17 帮助过:19人阅读

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

人气教程排行