php高效遍历,PHP字符串遍历性能居然远不如explode()

【 在 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值