Ryan
Ryan

Reputation: 15250

How can I return the memory allocation for an array in php?

I'd like to know how many bytes an array is allocated in memory.

$array = range(0,1000000000);
echo count($array);            // returns number of rows in array (1B);
echo sizeof($array);           // alias of count();

How can I make something like this work?

echo memory_allocated_to_array($array);

Here's a guess based on memory_get_usage():

$start_bytes = memory_get_usage();
$array = range(0,1000000000);
$end_bytes = memory_get_usage();
$array_bytes = ($end_bytes - $start_bytes);
echo $array_bytes;

But I suspect this is highly inaccurate when multiple processes are running (each with its own memory requirements).

Upvotes: 0

Views: 414

Answers (2)

EngineerCoder
EngineerCoder

Reputation: 1455

Edit: I have changed the answer:

$startMemory = memory_get_usage();
$array = range(1, 100000);
echo memory_get_usage() - $startMemory, ' bytes';

Regards.

Edit 2 :

Also try this:

$startMemory = memory_get_usage();
$array = new SplFixedArray(100000);
for ($i = 0; $i < 100000; ++$i) {
    $array[$i] = $i;
}
echo memory_get_usage() - $startMemory, ' bytes';

http://php.net/SplFixedArray

Upvotes: 0

Ryan
Ryan

Reputation: 15250

This is the current best answer of which I'm aware (as mentioned in the question above), but I will readily upvote and accept better answers.

$start_bytes = memory_get_usage();
$array = range(0,1000000000);
$end_bytes = memory_get_usage();
$array_bytes = ($end_bytes - $start_bytes);
echo $array_bytes;

Upvotes: 1

Related Questions