This article mainly introduces the PHP SPL standard library Splfixedarray Use instance, Splfixedarray mainly handles the array related main function, it is fixed the length, is quicker than the ordinary array processing, needs the friend to be possible to refer to under
Splfixedarray is mainly dealing with array-related main functions, unlike normal PHP array, it is fixed-length, and the number is the key name of the array, the advantage is more than normal array processing faster.
Check out my benchmark test for this machine:
?
1 2 3 4 5 6 7 8 9 10 |
Ini_set (' Memory_limit ', ' 12800M '); for ($size = 10000; $size < 10000000; $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; } |
The results are as follows:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
Testing size:10000 Array (): 0.004000186920166 Splarray (): 0.0019998550415039 Testing Array (): 0.01700115203 8574 Splarray (): 0.0090007781982422 testing size:160000 Array (): 0.050002098083496 Splarray (): 0.046003103256226 Test ing size:640000 Array (): 0.19701099395752 Splarray (): 0.16700983047485 testing size:2560000 Array (): 0.75704312324524 Splarray (): 0.67303895950317 |
Normally splfixedarray is faster than PHP array 20%~30%, so if you are dealing with a large number of fixed-length arrays, it is strongly recommended.
The Splfixedarray class summary is as follows:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
Splfixedarray implements iterator, arrayaccess, countable {/* Method/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 $ind Ex) public mixed offsetget (int $index) public void offsetset (int $index, mixed $newval) public void Offsetunset ( int $index) public void Rewind (void) public int setSize (int $size) public array toArray (void) public bool Valid (void) public void __wakeup (void)} |
Use Splfixedarray:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 The |
$arr = new Splfixedarray (4); $arr [0] = ' php '; $arr [1] = 1; $arr [3] = ' Pyth On '; //Traversal, $arr [2] is a null foreach ($arr as $v) {echo $v. Php_eol; //Get array length echo $arr->getsize (); 4 //increase array length $arr->setsize (5); $arr [4] = ' New one '; //catch exception try{echo $arr [ten];} catch (RuntimeException $e) {echo $e->getmessage ();} |