Does really SplFixedArray perform better than arrays?

Viewed 10875

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?

3 Answers

yes if you are using them with a fixed size.

If you are constantly changing the size for each new element to add could be slower and it it might not be the wrong usage too.

It is faster due to the implementation of array in PHP that those are not real array as a per definition in programming languages, but are instead associative array, implemented with a Hash table. (so array in PHP are basically Hash Tables)

Whilst the SplFixedArray is implemented using the "malloc" of C as a almost normal C array, of course wrapped in a small struct to keep track and manipulate the array as a per use cases.

UPDATE

At the same time since PHP 7.x there is no too much time difference in performances. The only way to know really is to do a benchmark based on your own use cases. If there is no special requirement, the normal PHP array is good enough.

Related