Is PHP's count() function O(1) or O(n) for arrays?

后端 未结 3 2155
终归单人心
终归单人心 2020-11-29 03:21

Does count() really count the all the elements of a PHP array, or is this value cached somewhere and just gets retrieved?

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-29 03:53

    In PHP 5+ the length is stored in the array so the counting is not done each time.

    EDIT: You also might find this analysis interesting: PHP Count Performance. Although the length of the array is maintained by the array, it still seems as though it is faster to hold on to it if you are going to call count() many times.

提交回复
热议问题