数组 函数
在线手册:中文  英文

sizeof

(PHP 4, PHP 5)

sizeof count() 的别名

说明

此函数是该函数的别名: count()


数组 函数
在线手册:中文  英文

用户评论:

umopdn [at] msn [dawt] com (2008-09-23 14:38:51)

a) Always try and use PHP's internal routines to iterate through objects of various types (arrays in most examples below).
Instead of interpreting your code to loop through them, they use their own internal routines which are much faster.
(This is why foreach () will run faster than manual interation)
b) It is _always_ good practice to leave as many static resulting functions outside of loops, having operations that return the exact same piece of data every iteration of the loop is not pretty on resources.
c) I agree with PixEye's remarks on sizeof(). In PHP it is just an alias for the true function count(). It has other meanings logically in other languages rather than the number of elements in an object. This should be avoided as it may confuse developers transitioning to PHP from other languages.

PixEye (2008-09-23 09:09:13)

I am quite surprised about previous posts. Here are my advices:
1/ prefer the count() function instead of sizeOf() as sizeOf() is only an alias of count() and does not mean the same in many other languages based on C (avoid ambiguity).
2/ prefer the powerful forEach() function to iterate over arrays.

rrf5000 at psu dot edu (2008-04-17 07:54:38)

The reason that the FOR loop runs faster on LARGE arrays if you save its size first (using count or sizeof) is pretty simple.  It's because if you use

<?php
for ($i 0$i sizeof($huge_array); $i++) {
  
//code
}
?>

every time the FOR loop checks its condition (is $i less than sizeof($huge_array) ), it must run the sizeof() function on $huge_array again.  This is what causes the extra processing time, which can become significant on larger arrays.

This has been thoroughly commented on both correctly and incorrectly in the User Contributed Notes for the count() function.

Edited 9-Jan-2013 by Levi Morrison (levim)

communiti.ch (2008-04-10 06:55:53)

If your array is "huge"
It is reccomended to set a variable first for this case:
THIS->
$max = sizeof($huge_array);
for($i = 0; $i < $max;$i++)
{
code...
}
IS QUICKER THEN->
for($i = 0; $i < sizeof($huge_array);$i++)
{
code...
}

svanegmond at tinyplanet dot ca (2008-03-13 11:12:22)

For people who use this kind of idiom:
for ($i=0; $i<sizeof($array); $i++) {
...
}
At least in PHP4, you will notice a large performance improvement if you switch to:
$max = sizeof($array);
for ($i=0; $i<$max; $i++) {
...
}
I had an array with a few thousand items in it, each of them a map with 5 key-value pairs, and just for'ing through the array took a second of CPU on a decent machine.

易百教程