I'm testing the SplFixedArray building an array with the days of the week, and I get the following results:
<?php
$days = new SplFixedArray(7);
$days[0] = "Monday";
$days[1] = "Tuesday";
$days[2] = "Wednesday";
$days[3] = "Thursday";
$days[4] = "Friday";
$days[5] = "Saturday";
$days[6] = "Sunday";
echo memory_get_peak_usage() . "\n"; //Returns 327688
echo memory_get_usage() . "\n"; //Returns 327140
echo memory_get_peak_usage(true) . "\n"; //Returns 524288
echo memory_get_usage(true) . "\n"; //Returns 524288
With traditional arrays:
<?php
$days = array();
$days[0] = "Monday";
$days[1] = "Tuesday";
$days[2] = "Wednesday";
$days[3] = "Thursday";
$days[4] = "Friday";
$days[5] = "Saturday";
$days[6] = "Sunday";
echo memory_get_peak_usage() . "\n"; //Returns 327528
echo memory_get_usage() . "\n"; //Returns 326820
echo memory_get_peak_usage(true) . "\n"; //Returns 524288
echo memory_get_usage(true) . "\n"; //Returns 524288
Does it make sense for you?
As illustrated by the benchmarks performed by the author of this article:
One can conclude that the memory footprint of SplFixedArray is indeed smaller, but noticeable only for a large amount of array elements. Because SplFixedArray is technically an instance of a class aswell, as opposed to traditional arrays, that is what is causing small arrays to be actually sightly more memory consuming if implemented by SplFixedArray, but as this extra few hundred of bytes remains constant, it becomes irrelevant as the size of the array grows.
Side note: don't micro-optimize, not every hammer is created for every nail. SplFixedArray is there for extreme cases, e.g. for arrays of hundreds of thousands of elements, where cutting down a few bytes of memory usage per element has a large impact on the overall memory usage; but don't bother using it unless you are really sure your array is or could be a potential bottleneck of the application.
A SplFixedArray is supposed to be faster than arrays. It doesn't say anything about memory consumption (which is what you're testing here). From http://php.net/manual/en/class.splfixedarray.php:
"The main differences between a SplFixedArray and a normal PHP array is that the SplFixedArray is of fixed length and allows only integers within the range as indexes. The advantage is that it allows a faster array implementation"
However, using an array of 100000 entries, reveals that it also uses less RAM:
$users = array();
for ($i=0;$i<100000;$i++) {
$users[$i] = array('id' => rand(), 'name' => 'default');
}
echo memory_get_peak_usage(true); //returns 31457280
$users = new SplFixedArray(100000);
for ($i=0;$i<100000;$i++) {
$users[$i] = array('id' => rand(),
'name' => 'default');
}
echo memory_get_peak_usage(true); //return 26738688
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With