Класс SplFixedArray

(PHP 5 >= 5.3.0, PHP 7)

Введение

Класс SplFixedArray обеспечивает базовую функциональность, предоставляемую массивами. Главное различие между SplFixedArray и обычным массивом PHP в том, что SplFixedArray имеет фиксированную длину, а в качестве индексов могут выступать только целочисленные значения. Преимущество данных ограничений заключается в более быстрой обработке массива.

Обзор классов

SplFixedArray implements Iterator , ArrayAccess , Countable {
/* Методы */
public __construct ([ int $size = 0 ] )
public int count ( void )
public mixed current ( void )
public static SplFixedArray fromArray ( array $array [, bool $save_indexes = true ] )
public int getSize ( void )
public int key ( void )
public void next ( void )
public bool offsetExists ( int $index )
public mixed offsetGet ( int $index )
public void offsetSet ( int $index , mixed $newval )
public void offsetUnset ( int $index )
public void rewind ( void )
public bool setSize ( int $size )
public array toArray ( void )
public bool valid ( void )
public void __wakeup ( void )
}

Примеры

Пример #1 Пример использования SplFixedArray

<?php
// Инициализация массива фиксированной длиной
$array = new SplFixedArray(5);

$array[1] = 2;
$array[4] = "foo";

var_dump($array[0]); // NULL
var_dump($array[1]); // int(2)

var_dump($array["4"]); // string(3) "foo"

// Увеличение размера массива до 10
$array->setSize(10);

$array[9] = "asdf";

// Сокращаем размер массива до 2-х
$array->setSize(2);

// Следующий код вызывает исключение RuntimeException: Index invalid or out of range
try {
    
var_dump($array["non-numeric"]);
} catch(
RuntimeException $re) {
    echo 
"RuntimeException: ".$re->getMessage()."\n";
}

try {
    
var_dump($array[-1]);
} catch(
RuntimeException $re) {
    echo 
"RuntimeException: ".$re->getMessage()."\n";
}

try {
    
var_dump($array[5]);
} catch(
RuntimeException $re) {
    echo 
"RuntimeException: ".$re->getMessage()."\n";
}
?>

Результат выполнения данного примера:

NULL
int(2)
string(3) "foo"
RuntimeException: Index invalid or out of range
RuntimeException: Index invalid or out of range
RuntimeException: Index invalid or out of range

Содержание

add a note add a note

User Contributed Notes 4 notes

up
33
artaxerxes
5 years ago
As the documentation says, SplFixedArray is meant to be *faster* than array. Do not blindly believe other people's benchmarks, and beextra careful with the user comments on php.net. For instance, nairbv's benchmark code is completely wrong. Among other errors, it intends to increase the size of the arrays, but always initialize a 20 elements SplFixedArray.

On a PHP 5.4 64 bits linux server, I found SplFixedArray to be always faster than array().
* small data (1,000):
    * write: SplFixedArray is 15 % faster
    * read:  SplFixedArray is  5 % faster
* larger data (512,000):
    * write: SplFixedArray is 33 % faster
    * read:  SplFixedArray is 10 % faster
up
10
chrisstocktonaz at gmail dot com
8 years ago
Note, that this is considerably faster and should be used when the size of the array is known. Here are some very basic bench marks:

<?php
for($size = 1000; $size < 50000000; $size *= 2) {
    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;
}
?>

OUTPUT
Testing size: 1000
Array(): 0.00046396255493164
SplArray(): 0.00023293495178223

Testing size: 2000
Array(): 0.00057101249694824
SplArray(): 0.0003058910369873

Testing size: 4000
Array(): 0.0015869140625
SplArray(): 0.00086307525634766

Testing size: 8000
Array(): 0.0024251937866211
SplArray(): 0.00211501121521

Testing size: 16000
Array(): 0.0057680606842041
SplArray(): 0.0041120052337646

Testing size: 32000
Array(): 0.011334896087646
SplArray(): 0.007631778717041

Testing size: 64000
Array(): 0.021990060806274
SplArray(): 0.013560056686401

Testing size: 128000
Array(): 0.053267002105713
SplArray(): 0.030976057052612

Testing size: 256000
Array(): 0.10280108451843
SplArray(): 0.056283950805664

Testing size: 512000
Array(): 0.20657992362976
SplArray(): 0.11510300636292

Testing size: 1024000
Array(): 0.4138810634613
SplArray(): 0.21826505661011

Testing size: 2048000
Array(): 0.85640096664429
SplArray(): 0.46247816085815

Testing size: 4096000
Array(): 1.7242450714111
SplArray(): 0.95304894447327

Testing size: 8192000
Array(): 3.448086977005
SplArray(): 1.96746301651
up
10
alex dot andrienko at gmail dot com
7 years ago
Memory footprint of splFixedArray is about 37% of a regular "array" of the same size.
I was hoping for more, but that's also significant, and that's where you should expect to see difference, not in "performance".
up
0
Anonymous
1 month ago
PHP Arrays are very fast, and faster overall, especially in PHP7. You almost never need this. There are some cases where using this is better than using arrays but beware that they aren't that obvious.
To Top