View Full Version : Array memory allocation

02-23-2012, 09:51 PM
I've got a situation where I need to assign values into an array, potentially several times during code execution. I'm wondering whether more memory is allocated via using array() multiple times, versus assigning into array elements. For example:

$a = array (1,2,3);
$a = array (4,5,6);
$a = array (7,8,9);

as opposed to:

$a = array (1,2,3);
$a[0] = 4;
$a[1] = 5;
$a[2] = 6;
$a[0] = 7;
$a[1] = 8;
$a[2] = 9;


02-23-2012, 09:57 PM
For an overwrite, the latter would be logically more efficient if these were real arrays. The former would require a malloc for each int*, while the latter is merely overwriting that of a[x].

In PHP though, there are no arrays, these are all hashtables, and offhand I don't know what type of storage is actually in use. PHP is a surprisingly efficient language in how it deals with things, so I would not be surprised if under the hood both result in the same effect. The only thing that would change that would be if $a is assigned without a reference to another variable, in which case you are guaranteed to malloc more data (since PHP works in copy on write context).

02-23-2012, 10:02 PM
I certainly had no idea that a simple linear array like that was treated as a hash table in PHP! Thanks for the input Fou-Lu, I think I can go with "Plan 1" given what you're saying.


02-24-2012, 08:12 AM
I certainly had no idea that a simple linear array like that was treated as a hash table in PHP!

I'd rather say that PHP treats associative and linear arrays the same as it uses the same construct (array()) to define them.

maybe the closest to a standard array (at least from behaviour) is SplFixedArray.

02-24-2012, 02:33 PM
Yep, neither associative or linear are arrays in PHP. Both are hashtables. splFixedArray will be the closest, but still not an array since its an object:

typedef union _zvalue_value {
long lval;
double dval;
struct {
char *val;
int len;
} str;
HashTable *ht;
zend_object obj;
} zvalue_value;

A PHP variable has to be one of those unioned values.

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum