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++) {}

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.

The first version is best used if the loop is expected to have many iterations and $key won't change in the process.

The second one is best used if the loop is updating $key and you need to recalculate it, or, when recalculating it doesn't affect your performance.