note 96236 added to function.count
| From: | pinkgothic at gmail dot com | Date: | Tue, 16 Feb 2010 15:09:23 +0000 |
| Subject: | note 96236 added to function.count | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-166007@lists.php.net to get a copy of this message | ||
yarolan at mail dot ru's observation is, to my relief, no longer true (php 5.3.1, possibly
earlier).
Using count() in a loop is approximately a linear doubling of cost compared to assigning it before
the loop (e.g. 0.2 instead of 0.1). The overhead may at this point simply be from calling a function
instead of just reading a variable (evidently by now arrays keep track of the amount of elements
they have).
This is good news for those of you who do semi-complex array handling in your loops that sometimes
changes count() and sometimes doesn't (making keeping-track-of-the-count-in-a-variable-yourself
tedious); or those of you who value semantic legibility over performance to a degree. :)
Re: ravenswd at gmail dot com
legobuff at hotmail dot com's code does not contain an error, because it doesn't set out
to retrieve the max' key, just the key of the last element in the array. It does that. :)
If you're looking for the max' key, then, indeed, it would have to look something like
this:
<?php
ksort($yourArray);
end($yourArray);
$index = key($yourArray);
?>
But! ravenswd at gmail dot com's solution is quicker.
I've not checked, but I imagine the ksort-end-key variant may be somewhat less memory intensive
due to lack of another array being created, hence might be useful in a constellation where memory
might be more of an issue than CPU. Either way, I figured I'd share.
----
Server IP: 217.160.72.57
Probable Submitter: 80.153.202.193
----
Manual Page -- http://www.php.net/manual/en/function.count.php
Edit -- https://master.php.net/note/edit/96236
Del: integrated -- https://master.php.net/note/delete/96236/integrated
Del: useless -- https://master.php.net/note/delete/96236/useless
Del: bad code -- https://master.php.net/note/delete/96236/bad+code
Del: spam -- https://master.php.net/note/delete/96236/spam
Del: non-english -- https://master.php.net/note/delete/96236/non-english
Del: in docs -- https://master.php.net/note/delete/96236/in+docs
Del: other reasons-- https://master.php.net/note/delete/96236
Reject -- https://master.php.net/note/reject/96236
Search -- https://master.php.net/manage/user-notes.php