Is this foreach loop responsible for god killing cats?

As taken from https://stackoverflow.com/questions/4891301/top-bad-practices-in-php

Is this similar code killing kittens, too?

foreach (file("longFile.txt") as $line) {
    // ouch! Kitten killed
}

??

For those who have no idea what am I talking about:

Is PHP getting longFile.txt everytime it goes to next line of file or no? Talking about this code:

foreach (file("longFile.txt") as $line) {
        // something
}

In the linked question the for loop incurs a performance hit by calling count on every iteration. foreach uses internal pointers to iterate through the array passed to it.

In your example file() will be called once and the resulting array will be passed to foreach which will iterate through it, thus the kittens are saved. Happy Caturday!


It shouldn't be killing any kittens, since, in order for PHP to get the following line of the file, it has to know the position of the file pointer since the previous line that was pulled off. You are only advancing the iterator, which maintains a reference to the file object.

Also, it's bad practice to be opening a file like that; you should have a variable to store it in and close it when you're done.


You want to use a Duff Device to unroll the loop: http://de.wikipedia.org/wiki/Duff%E2%80%99s_Device. This would be faster then foreach and faster then for loop without using count() on each iteration and it would be faster then concatenating and rtrim the string but the same like using implode().

链接地址: http://www.djcxy.com/p/10142.html

上一篇: 在PHP 5.4.0以前版本的一个匿名函数中使用`$ this`

下一篇: 这个foreach循环负责上帝杀死猫吗?