You are here

function _coder_performance_in_array_warning in Coder 5

1 string reference to '_coder_performance_in_array_warning'
coder_performance_reviews in includes/coder_performance.inc
@file This include file implements coder functionality for Performance

File

includes/coder_performance.inc, line 111
This include file implements coder functionality for Performance

Code

function _coder_performance_in_array_warning() {
  return array(
    '#warning' => t('<code class="good">if (isset($array[\'foo\']))</code> is faster than <code class="bad">if (in_array(\'foo\', $array))</code>'),
    '#description' => t('Another common operation in PHP scripts is array searching. This process can be quite slow as regular search mechanism such as <code>in_array()</code> or manual implementation work by iterating through the entire array. This can be quite a performance hit if you are searching through a large array or need to perform the searches frequently. So what can you do? Well, you can do a trick that relies upon the way that Zend Engine stores array data. Internally arrays are stored inside hash tables when their array element (key) is the key of the hashtables used to find the data and result is the value associated with that key. Since hashtable lookups are quite fast, you can simplify array searching by making the data you intend to search through the key of the array, then searching for the data is as simple as <code>isset($foo[$bar]))</code>. This search mechanism is way faster than manual array iteration, even though having string keys maybe more memory intensive than using simple numeric keys.<br /><br />
        Example:<br />
        <code>$keys = array("apples", "oranges", "mangoes", "tomatoes", "pickles");<br />
        if (in_array(\'mangoes\', $keys)) { ... }<br /></code>
        <br />
        vs.<br />
        <br />
        <code>$keys = array("apples" => 1, "oranges" => 1, "mangoes" => 1, "tomatoes" => 1, "pickles" => 1);<br />
        if (isset($keys[\'mangoes\'])) { ... }<br /></code>
        <br />
        The bottom search mechanism is roughly 3 times faster.'),
  );
}