duansao20000508 2014-10-22 06: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 06: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部