星期三, 九月 10, 2008

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

固定長度的字串(假設是 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() 大獲全勝, 還是不要懶惰, 雖然要寫比較多行, 但是速度會快不少.

相關標籤

this is comment icon 太幸運了~ [回覆]

今天遇到問題~
剛好就找到了~
馬上就解決了~
真的太幸運了~

Comment by php初學者 (09/10/2008 17:19)

this is comment icon 回 php初學者 [回覆]

呵呵, 恭喜~ :D

Comment by Tsung (09/10/2008 20:09)

this is comment icon mb_substr [回覆]

哎呀~ 應該要測試一下 mb_substr :-D

Comment by rsii (09/15/2008 12:37)

this is comment icon 回 rsii [回覆]

mb_substr 比 substr 慢 3 倍, substr 4秒, mb_substr 12秒. :)

Comment by Tsung (09/15/2008 13:31)
Add this page to del.icio.us Add this page to Yahoo Taiwan's bookmark Add this page to MyShare

發表迴響

標題

內容 (限制 1000 字)

暱稱

電子郵件

個人網頁


 authimage


PS: 若無法留言, 請先確認是否有打開 JavaScript, 造成您的困擾, 實在萬分對不起 Orz...(如果無法留言, 勞煩可以發信給我好嗎? 謝謝.)
PS2: 若您的留言被誤判, 我都會再自行看過, 不需要一直重覆張貼~