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

后端 未结 3 2160
终归单人心
终归单人心 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:59

    PHP stores the size of an array internally, but you're still making a function call when which is slower than not making one, so you'll want to store the result in a variable if you're doing something like using it in a loop:

    For example,

    $cnt = count($array);
    for ($i =0; $i < $cnt; $i++) {
       foo($array[$i]);
    }
    

    Additionally, you can't always be sure count is being called on an array. If it's called on an object that implements Countable for example, the count method of that object will be called.

提交回复
热议问题