Does really SplFixedArray perform better than arrays?

Isra picture Isra · Aug 6, 2012 · Viewed 9.5k times · Source

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?

Answer

Mahn picture Mahn · Aug 6, 2012

As illustrated by the benchmarks performed by the author of this article:

http://www.johnciacia.com/wp-content/uploads/2011/01/3.png

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.