duansao20000508 2014-10-22 14:32
浏览 7
已采纳

PHP循环上下文查询

A question that has always puzzled me is why people write it like the first version when the second version is smaller and easier to read. I thought it might be because php calculates the strlen each time it iterates. any ideas?

FIRST VERSION

    for ($i = 0, $len = strlen($key); $i < $len; $i++) {}

You can obviously use $len inside the loop and further on in the code, but what are the benefits over the following version?

SECOND VERSION

    for ($i = 0; $i < strlen($key); $i++) {}
  • 写回答

2条回答 默认 最新

  • dongwei1954 2014-10-22 14:38
    关注

    It's a matter of performance.

    Your first version of the for loop will recaculate the strlen every time and thus, the performances could be slowed down.

    Even though it wouldn't be significant enough, you could be surprised how much the slow can be exponantial sometimes.

    You can see here for some performances benchmarks with loops.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集