PHP.mk документација

SplFixedArray

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

class.splfixedarray.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека class.splfixedarray.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
SplFixedArray

Референца за `class.splfixedarray.php` со подобрена типографија и навигација.

class.splfixedarray.php

Класата SplFixedArray

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

Вовед

Класата SplFixedArray ги обезбедува главните функционалности на низата. Главната разлика помеѓу SplFixedArray и нормална PHP низа е тоа што SplFixedArray мора рачно да се преозначи и дозволува само цели броеви во опсегот како индекси. Предноста е што користи помалку меморија од стандардна array.

Синопсис на класата

/* Методи */
public __construct(int $size = 0)
public count(): int
public current(): mixed
public static fromArray(array $array, bool $preserveKeys = true): SplFixedArray
public getSize(): int
public key(): int
public next(): void
public offsetExists(int $index): bool
public offsetGet(int $index): mixed
public offsetSet(int $index, mixed $value): void
public offsetUnset(int $index): void
public rewind(): void
public __serialize(): array
public setSize(int $size): true
public toArray(): array
public __unserialize(array $data): void
public valid(): bool
}

Дневник на промени

Верзија = NULL
8.2.0 На SplFixedArray::__serialize() and SplFixedArray::__unserialize() додадени се магични методи на SplFixedArray.
8.1.0 SplFixedArray implements JsonSerializable now.
8.0.0 SplFixedArray implements IteratorAggregate сега. Претходно, Итератор беше имплементирано наместо тоа.

Примери

Пример #1 SplFixedArray пример за употреба

<?php
// Initialize the array with a fixed length
$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"

// Increase the size of the array to 10
$array->setSize(10);

$array[9] = "asdf";

// Shrink the array to a size of 2
$array->setSize(2);

// The following lines throw a 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";
}
?>

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

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

Содржина

Белешки од корисници 6 белешки

artaxerxes
пред 13 години
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
herhor67 на interia точка pl
пред 6 години
Memory usage for arrays of 1132766 ints (data derived from some 1kx1k img):
Regular:  76453160B (67.5B/int)
SplFixed: 18898744B (16.7B/int)

In my application, SFA uses 75% less RAM, which is a life-saver.

Speed comparison:
Regular: 449ms
SplFixed (resized before every element): 791ms
SplFixed (fully preallocated): 392ms
SplFixed (preall-d to 1M and then resized): 547ms

Pros and cons:
+ much more efficient RAM-wise
+ a bit faster if max size is known
~ a bit slower if max size is only approximated
- much slower if max size is not known
- cannot be used with most array functions

To sum up:
SplFixedArray is a very good choice for storing giant amount of data, though only as long as you at least roughly know the size and can work without array functions.
chrisstocktonaz на gmail точка com
пред 16 години
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
alex точка andrienko на gmail точка com
пред 15 години
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".
Анонимен
пред 8 години
getSize() and count() return the same value
CK
3 години пред
Be warned that SplFixedArray does not provide all of the main functionalities of array. For example, it does not support array_slice. SplFixedArray should be far more efficient at supporting such array operations than normal arrays (since it should be simply a contiguous slice). Check that all your main array functions are really supported before trying to use SplFixedArray instead of array. With JIT in PHP8, some loops to polyfill these are perhaps now realistic, but still not as fast as native functions.
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.