note 110232 added to language.types.array
| From: | cromney at pointslope dot com | Date: | Wed, 03 Oct 2012 15:49:12 +0000 |
| Subject: | note 110232 added to language.types.array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-191117@lists.php.net to get a copy of this message | ||
One thing to be careful of is making any assumptions about the underlying implementation with
respect to performance. For example, the documentation talks about hash-maps, which might lead you
to expect O(1) key lookups.
<?php
function find_val($n) {
$t = array();
$last = null;
for ($x = 0; $x < $n; $x++) {
$last = "" . $x;
$t[] = $last;
}
var_dump(in_array($last, $t));
}
function find_key($n) {
$t = array();
$last = null;
for ($x = 0; $x < $n; $x++) {
$last = "" . $x;
$t[$last] = true;
}
var_dump(array_key_exists($last, $t));
}
$n = 1600000;
find_val($n);
// Time taken: 1123ms
find_key($n);
// Time taken: 803
/*
Additional Timings:
n find_val(ms) find_key(ms)
100000 99 82
200000 169 130
400000 301 217
800000 570 416
1600000 1123 803
*/
?>
In my tests, both in_array and array_key_exists exhibited the same order of growth.
----
Server IP: 69.147.83.199
Probable Submitter: 65.9.106.248
----
Manual Page -- http://www.php.net/manual/en/language.types.array.php
Edit -- https://master.php.net/note/edit/110232
Del: integrated -- https://master.php.net/note/delete/110232/integrated
Del: useless -- https://master.php.net/note/delete/110232/useless
Del: bad code -- https://master.php.net/note/delete/110232/bad+code
Del: spam -- https://master.php.net/note/delete/110232/spam
Del: non-english -- https://master.php.net/note/delete/110232/non-english
Del: in docs -- https://master.php.net/note/delete/110232/in+docs
Del: other reasons-- https://master.php.net/note/delete/110232
Reject -- https://master.php.net/note/reject/110232
Search -- https://master.php.net/manage/user-notes.php