Re: Hidden costs of PHP arrays?

From: Date: Wed, 28 Jan 2009 01:17:32 +0000
Subject: Re: Hidden costs of PHP arrays?
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-287258@lists.php.net to get a copy of this message
Robert Cummings wrote:
On Wed, 2009-01-28 at 10:38 +1100, Clancy wrote:
PHP arrays permit extremely concise programming; for example if I have all my contacts in an array $contacts, I can write: $my_phone_no = $contacts['clancy']['phone']; However it is clear that there must be a lot going on behind the scenes to achieve this simple result, as it requires some sort of search procedure. Is it possible to give any indication of the overheads and memory costs that are involved in such a statement, and of how well the search procedure is implemented? Also what the relative virtues of defining the same set of fields for every contact, as against either defining only the fields which actually hold values, as in the following examples? a: $contacts['clancy']['home_address'] = 'jkjkjk'; $contacts['clancy']['home_phone'] = 0123 4567; $contacts['clancy'][' office_address''] = ''; $contacts['clancy']['office_phone'] = ''; $contacts['joe']['home_address'] = ''; $contacts['joe']['home_phone'] = ''; $contacts['joe']['office_address'] = 'jsfvkl'; $contacts['joe']['office_phone'] = 'jsfvkl'; b; $contacts['clancy']['home_phone'] = 0123 4567; $contacts['clancy']['home_address'] = 'jkjkjk'; $contacts['joe']['office_address'] = 'jsfvkl'; $contacts['joe']['office_phone'] = 'jsfvkl'; And is there any advantage in always assigning the keys in the same order?
Lookup is O( lg n ). Since your examples above are nested 2 levels deep then it's actually 2 * O( lg n ) which is O( lg n ). But really, the variable itself, $contacts is probably also looked up and it is also O( lg n ) and of course 3 * O( lg n ) is still O( lg n ). Moving along... for arbitrary depth paths, you'd be talking O( m lg n ) but for realistic cases you'll not get deep enough for that to matter much. Either way, if you are looping over an array and always accessing X levels deep, you might want to create a temporary variable that is level X - 1 (unless that's not a possible option). Cheers, Rob.
rob; go apply for a job at yahoo - that's one of there interview questions for new developers [describe o notation] <is impressed - v nice answer>

« previous php.general (#287258) next »