note 73695 deleted from function.array-key-exists by nlopess

From: Date: Sun, 11 Mar 2007 12:42:32 +0000
Subject: note 73695 deleted from function.array-key-exists by nlopess
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-124323@lists.php.net to get a copy of this message
Note Submitter: inker2576 at yahoo dot com ---- 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.

« previous php.notes (#124323) next »