PHP 分割字串 Function 的速度比較(substr/sscanf/preg_match)---substr最快!

简介: 固定長度的字串(假設是 06481a63041b578d702f159f520847f8), 要照固定格式做切割, 使用 PHP 要怎麼切會比較快? 註: 要將此字串切成 => 06 / 48 / 1a63041b578d702f159f520847f8 這三個字串.

固定長度的字串(假設是 06481a63041b578d702f159f520847f8), 要照固定格式做切割, 使用 PHP 要怎麼切會比較快?

註: 要將此字串切成 => 06 / 48 / 1a63041b578d702f159f520847f8 這三個字串.

 

寫簡單的程式做個測試, 來比較 substr / sscanf / preg_match 的速度.

先設 $a = '06481a63041b578d702f159f520847f8';, 再執行下面程式做測試(全部都跑 100萬次的數據):

  • 使用 substr 程式執行花 4.08482551575 秒:

    $x[0] = substr($a, 0, 2);
    $x[1] = substr($a, 2, 2);
    $x[2] = substr($a, 4, 28);

  • 使用 sscanf 程式執行花 5.26213645935 秒 (與 substr 差 -5.26213645935)

    list($x[0], $x[1], $x[2]) = sscanf($a, '%2s%2s%28s');
    註: $x = sscanf($a, '%2s%2s%28s'); // 耗費時間增加到 8秒, 會比 preg_match 更慢.

  • 使用 preg_match 程式執行花 7.58504867554 秒 (與 substr 差: -7.58504867554)

    preg_match('/^(\w{2})(\w{2})(\w{28})$/', $a, $match);
    $x[0] = $match[1];
    $x[1] = $match[2];
    $x[2] = $match[3];

結論, substr() 大獲全勝, 還是不要懶惰, 雖然要寫比較多行, 但是速度會快不少.

如何联系我:【万里虎】www.bravetiger.cn 【QQ】3396726884 (咨询问题100元起,帮助解决问题500元起) 【博客】http://www.cnblogs.com/kenshinobiy/
目录
相关文章
|
10月前
|
PHP
PHP报错Call to undefined function utf8_decode()的解决方案
PHP报错Call to undefined function utf8_decode()的解决方案
|
10月前
|
PHP
php数组学习(1):固定格式的字符串分割成数组后内容去重
php数组学习(1):固定格式的字符串分割成数组后内容去重
31 0
|
10月前
|
PHP
漏刻有时环境部署:php安装提示Can‘t use function return value in write context
漏刻有时环境部署:php安装提示Can‘t use function return value in write context
38 0
|
10月前
|
PHP
php函数基础学习:array_chunk() 函数把一个数组分割为新的数组块
php函数基础学习:array_chunk() 函数把一个数组分割为新的数组块
41 0
|
消息中间件 PHP
laravel6 使用rabbitmq报错:Call to a member function make() on null at Queue\\Jobs\\Job.php:215
laravel6 使用rabbitmq报错:Call to a member function make() on null at Queue\\Jobs\\Job.php:215
136 0
|
PHP Windows
php使用register_tick_function来定位执行慢的代码
php使用register_tick_function来定位执行慢的代码
168 0
|
存储 PHP
PHP 零基础入门笔记(9):函数 function
PHP 零基础入门笔记(9):函数 function
PHP 正则表达式preg_match
PHP 正则表达式preg_match
|
PHP
【PHP】preg_match函数
【PHP】preg_match函数
100 0
【PHP】preg_match函数
|
PHP
【PHP报错集锦】 Maximum function nesting level of ‘256‘ reached, aborting!
【PHP报错集锦】 Maximum function nesting level of ‘256‘ reached, aborting!
417 0
【PHP报错集锦】 Maximum function nesting level of ‘256‘ reached, aborting!