The Performance of an Associative Array in PHP
PHP is a server-based language for creating interactive Web applications and rendering user content on demand. It supports a variety of data collection classes in its array construct, including indexed arrays and associative arrays. With a large number of users, performance of your code can become an issue. Though associative arrays don't require significant CPU overhead, they do need more memory to store in RAM as your program is running.
-
Indexed Arrays
-
A standard indexed array in PHP and other languages contains a series of subsequent value indexes mapped to data values. A data value is accessed by referencing the index, or position in the array.
$my_array = array(1, 2, 3, 4, 5);
Accessing the element "$my_array[0]" returns the value 1. Indexed arrays are best for storing and accessing structured data. It would be inefficient to do the following, as it would fill in the gaps in index values, taking up a very large amount of memory:
$my_array[] = 7;
$my_array[13] = 5;
$my_array[76] = -4;
Associative Arrays
-
As opposed to indexed arrays, PHP associative arrays contain a series of key-value pairs. The data values are accessed by referencing the key that can be either a unique string or numeric value. The inefficient example above can be better written as an associative array:
$my_array(0 => 5, 13 => 5, 75 => -4);
$my_array("one" => 1, "two" => 2, "seventeen" => 17); -
CPU Performance
-
PHP is optimized for the processing of strings. Having a string as the key for an associative array doesn't produce much overhead. When accessing an element in an associative array in PHP, the array isn't searched from beginning to end to determine if any of the keys match. Instead, a key in an associative array maps to an index value, with no additional overhead in lookup time over indexed arrays.
Memory Performance
-
Since PHP associative arrays store a key-value pair, as opposed to only a value, they require additional memory overhead, space your program uses in RAM while running, when compared to indexed arrays. This additional memory is normally negligible unless you're using very large arrays. In this case, it may be prudent to split up very large arrays into a subset of arrays that can be accessed as needed.
-
References
- Photo Credit Creatas/Creatas/Getty Images