SPL data structure 3-splfixedarray

Time:2021-7-27

Splfixedarray is a fixed length array provided in PHP. The array in PHP language is particularly powerful. It can realize data structures such as stack, queue, list, dictionary and so on. Its bottom layer is based on hash table. The array represented by splfixedarray is close to the array in C go and other languages. Its length is fixed, and the index subscript is integers. The advantage is that it uses less memory than a standard array.

performance testing

The measured splfixedarray is better than array in terms of time and memory usage

for($size = 10000; $size < 50000000; $size *= 4) {
    echo PHP_EOL . "Testing size: $size" . PHP_EOL;
    for($s = microtime(true), $container = Array(), $i = 0; $i < $size; $i++) $container[$i] = NULL;
    echo "Array(): " . (microtime(true) - $s) . PHP_EOL;

    for($s = microtime(true), $container = new SplFixedArray($size), $i = 0; $i < $size; $i++) $container[$i] = NULL;
    echo "SplArray(): " . (microtime(true) - $s) . PHP_EOL;
}

use

//Initialize the array with a fixed length
$arr    = new SplFixedArray(4);
$arr[0] = 'php';
$arr[1] = 1;
$arr[3] = 'python';
//If the index subscript is exceeded, an array out of bounds runtimeException will be reported:
//$arr[4] = 'python';
$arr->setSize(5);
//No more errors are reported here
$arr[4] = 'python';

Echo "default subscript". PHP_ EOL;
var_dump($arr[2]);


Echo "subscript is 0:". $arr [0]. PHP_ EOL;
//You can also get the element here
Echo "subscript is \" 0 \ ":". $arr ["0"]. PHP_ EOL . PHP_ EOL;


Echo "start traversal:". PHP_ EOL;
foreach ($arr as $v) {
    echo $v . PHP_EOL;
}

Echo "array length:". Count ($ARR). PHP_ EOL;
Echo "use the count method to get the array length:" $arr - > count(). PHP_ EOL;

Previous:SPL data structure 2-heap, maximum heap, minimum heap

Next:SPL data structure 4-splobjectstorage