php foreach, why using pass by reference of a array is fast?

前端 未结 2 1438
忘掉有多难
忘掉有多难 2020-12-16 19:46

Below is a test of php foreach loop of a big array, I thought that if the $v don\'t change, the real copy will not happen because of copy on write

2条回答
  •  南方客
    南方客 (楼主)
    2020-12-16 20:26

    Actually, I disagree a bit with the first answer. Most importantly, as the comments say, the tests are not the same. Here's the fully-isolated tests, testing ONLY the loops.

    Version 1:

    Version 2:

    Notice that in the fully-isolated form, the second tests show NO differences, while the first one does. Why?

    The answer is that the array has an internal pointer for things like foreach. It can be accessed by calls like current. When you do foreach with a reference, the original array's pointers is used. When you pass by value, the array internals must be copied as soon as the foreach executes, even if the values are maintained somehow by the engine. Thus, the penalty.

提交回复
热议问题