gentrobot
gentrobot

Reputation: 671

Why is using a variable in a for loop faster than some function output?

On Symfony blog, in support of Symfony being faster, it was mentioned that

for ($i = 0; $i<count($my_array); $i++)

is slower as compared to

for ($i = 0, $count = count($my_array); $i<$count; $i++)

The reason they had mentioned was "Because we measured". But what exactly is the reason for the latter being faster out of the two approaches mentioned above ?

Upvotes: 0

Views: 70

Answers (1)

anstarovoyt
anstarovoyt

Reputation: 8136

The first 'for' calculates count of $my_array every iterate. The second 'for' calculates count once.

Upvotes: 4

Related Questions