note 73695 added to function.array-key-exists

From: Date: Tue, 06 Mar 2007 23:11:36 +0000
Subject: note 73695 added to function.array-key-exists
Groups: php.notes 
Request: Send a blank email to php-notes+get-124180@lists.php.net to get a copy of this message
It's worth pointing out that this function can be very slow on large arrays, which I discovered the hard way (and I'm using PHP 5.1.6, for what it's worth). I had used this code in the core of a search engine: <?php ... if (array_key_exists($keyword, $SearchKeywords)) { $keyword_stats = $SearchKeywords[$keyword]; ... } ... ?> The $SearchKeywords array contains about 15,000 entries, and each entry is of the form: string => array. $keyword is always a string. By all rights, that code should run quickly, but to my great surprise, careful profiling showed it was taking about 10 msec each time array_key_exists() was called, and array_key_exists() was the culprit. I replaced it with this seemingly-identical code: <?php ... $keyword_stats = @$SearchKeywords[$keyword]; if (is_array($keyword_stats)) { ... } ... ?> When I replaced it, execution time went from 10 msec per keyword to 0.1 msec per keyword, a speedup of about 100 times. My guess is that array_key_exists() may use a linear search through the array, or at least some other O(n) solution. The average search time in my search engine went from about 30 msec to about 1.5 msec as a result. In short: Don't use array_key_exists() on large arrays if you can avoid it, because it's a much slower function than it appears to be. ---- Server IP: 216.194.113.175 Probable Submitter: 71.225.5.53 ---- Manual Page -- http://www.php.net/manual/en/function.array-key-exists.php Edit -- https://master.php.net/note/edit/73695 Del: integrated -- https://master.php.net/note/delete/73695/integrated Del: useless -- https://master.php.net/note/delete/73695/useless Del: bad code -- https://master.php.net/note/delete/73695/bad+code Del: spam -- https://master.php.net/note/delete/73695/spam Del: non-english -- https://master.php.net/note/delete/73695/non-english Del: in docs -- https://master.php.net/note/delete/73695/in+docs Del: other reasons-- https://master.php.net/note/delete/73695 Reject -- https://master.php.net/note/reject/73695 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#124180) next »