php分割字符串方法速度比較(substr/sscanf/preg_match)
2013-10-31 09:59
1446 查看
固定長度的字串(假設是 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() 大獲全勝
註: 要將此字串切成 => 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() 大獲全勝
相关文章推荐
- PHP 分割字串 Function 的速度比較(substr/sscanf/preg_match)---substr最快!
- PHP的preg_match匹配字符串长度问题解决方法
- PHP的preg_match匹配字符串长度问题解决方法
- 向PHP要效率——加快你的代码执行速度(strpos 快于 preg_match 快于 strstr 快于 ereg)
- php使用substr()和strpos()联合查找字符串中某一特定字符的方法
- PHP使用preg_split()分割特殊字符(元字符等)的方法分析
- PHP中substr_count()函数获取子字符串出现次数的方法
- php使用substr()和strpos()联合查找字符串中某一特定字符的方法
- php实现将字符串按照指定距离进行分割的方法
- php把字符串指定字符分割成数组的方法
- 测试PHP preg_match()函数信息泄露方法介绍
- php preg_match($p, $str, $match)方法简介
- php preg_match方法
- php 正则获取字符串中的汉字preg_match_all
- PHP substr 截取字符串出现乱码问题解决方法[utf8与gb2312]
- php通过数组实现多条件查询实现方法(字符串分割)
- php:查找字符串的相关方法[strpos,stripos,strrpos,strripos,substr,stristr,strstr]
- PHP实例——字符串分割(完美支持中英文,兼容mb_substr)
- PHP 中文字符串截取无乱码的方法以及php汉字截取函数_preg_split()
- PHP中substr_count()函数获取子字符串出现次数的方法