固定長度的字串(假設是 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() 大獲全勝

相关文章:

  • 2022-02-15
  • 2021-12-25
  • 2022-12-23
  • 2022-12-23
  • 2021-08-27
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-07-12
  • 2022-12-23
  • 2021-06-02
  • 2022-01-08
  • 2021-11-22
  • 2021-09-30
  • 2022-12-23
相关资源
相似解决方案