PHP array: count or sizeof?

后端 未结 8 911
慢半拍i
慢半拍i 2020-11-30 21:27

To find the number of elements in a PHP $array, which is faster/better/stronger?

count($array) or sizeof($array) ?

Ed

8条回答
  •  借酒劲吻你
    2020-11-30 22:16

    According to phpbench:

    Is it worth the effort to calculate the length of the loop in advance?

    //pre-calculate the size of array
    $size = count($x); //or $size = sizeOf($x);
    
    for ($i=0; $i<$size; $i++) {
        //...
    }
    
    //don't pre-calculate
    for ($i=0; $i

    A loop with 1000 keys with 1 byte values are given.

                      +---------+----------+
                      | count() | sizeof() |
    +-----------------+---------+----------+
    | With precalc    |     152 |      212 |
    | Without precalc |   70401 |    50644 |
    +-----------------+---------+----------+  (time in µs)
    

    So I personally prefer to use count() instead of sizeof() with pre calc.

提交回复
热议问题