【 在 bitkevin (kevin) 的大作中提到: 】
: 标 题: PHP字符串遍历性能居然远不如explode()
: 发信站: 水木社区 (Thu Nov 15 20:06:48 2012), 站内
: 同事发现的一个问题。字符串源类似:"aaa bbb ccc ddd eee"。想找出空格切开后的第N个字串,两个思路:
: 1. explode()切开直接取
: 2. 遍历字符串,一趟搞定
: 我预判2的性能更好,结果1的性能几乎是2的五倍。测试代码:
: <?php
: $s = "aaa bbb ccc ddd";
: for ($i = 0; $i
: // $arr = explode(' ', $s);
: // $t = $arr[2];
: // continue;
: $t = '';
: $cnt = 0;
: $j = 0;
: $len = strlen($s);
: while ($j
: $c = $s{$j};
: if ($c == ' ') {
: $cnt++;
: if ($cnt == 2) {
: $j++;continue;
: }
: }
: if ($cnt == 2) {
: $t .= $c;
: }
: if ($cnt == 3) {
: break;
: }
: $j++;
: }
: }
: echo $t;
: 2是1耗时的五倍:
: 1. 1.26s user 0.02s system 97% cpu 1.315 total
: 2. 5.30s user 0.02s system 99% cpu 5.337 total
: 难以理解,于是写了C的代码做性能对比。
: #include
: int main()
: {
: const char *s = "aaa bbb ccc ddd";
: char buf[10] = {0};
: int i;
: for (i = 0; i
: char *t = buf;
: const char *p = s;
: int cnt = 0;
: while (*p != '\0') {
: if (*p == ' ') {
: cnt++;
: if (cnt == 2) {
: p++;continue;
: }
: }
: if (cnt == 2) {
: *t++ = *p;
: }
: if (cnt == 3) {
: break;
: }
: p++;
: }
: *t = '\0';
: }
: printf("%s\n", buf);
: return 0;
: }
: 耗时:0.07s user 0.00s system 84% cpu 0.081 total
: 结论是PHP遍历字符串处理确实性能不高,不如explode()来的简洁有力。
: --
: talk is cheap, show me the code