Home > Article > Backend Development > Array and SplFixedArray comparison (code example)
The essence of PHP is the use of arrays. If arrays are used well, they can be used in all data structures. There is a good thing called SPL, which has many data structures for us to use, and the performance is much better than what we can achieve using arrays.
Today let’s take a look at SplFixedArray, as the name suggests, a fixed-size array. When instantiating, specify the array size. The array cannot be expanded or reduced during use.
So if you perform dynamic operations on the array, it may not be suitable to use it, and the index of SplFixedArray can only be numbers and cannot be used as a key value array.
The following is the test of 100W read and write performance and memory usage of Array and SplFixedArray
Code
<?php define('TEST_COUNT', 1000000); $memory = memory_get_usage(); $writeTime = microtime(true); $arr = []; for($i = 0; $i < TEST_COUNT; ++$i) { $arr[] = $i; } $writeTime = microtime(true) - $writeTime; $readTime = microtime(true); for($i = 0; $i < TEST_COUNT; ++$i) { $value = $arr[$i]; } $readTime = microtime(true) - $readTime; $memory = memory_get_usage() - $memory; echo '[Array]', PHP_EOL, 'Memory: ', $memory, ' bytes', PHP_EOL, 'Write Time: ', $writeTime, 's', PHP_EOL, 'Read Time: ', $readTime, 's', PHP_EOL; $memory = memory_get_usage(); $writeTime = microtime(true); $splFixedArray = new SplFixedArray(TEST_COUNT); for($i = 0; $i < TEST_COUNT; ++$i) { $splFixedArray[$i] = $i; } $writeTime = microtime(true) - $writeTime; $readTime = microtime(true); for($i = 0; $i < TEST_COUNT; ++$i) { $value = $splFixedArray[$i]; } $readTime = microtime(true) - $readTime; $memory = memory_get_usage() - $memory; echo '[SplFixedArray]', PHP_EOL, 'Memory: ', $memory, ' bytes', PHP_EOL, 'Write Time: ', $writeTime, 's', PHP_EOL, 'Read Time: ', $readTime, 's', PHP_EOL;
Running results
[Array] Memory: 33558608 bytes Write Time: 0.083034038543701s Read Time: 0.022516965866089s [SplFixedArray] Memory: 16003208 bytes Write Time: 0.037343978881836s Read Time: 0.022947072982788s
Conclusion
Memory usage: SplFixedArray can save more than half the memory than Array
Write performance: SplFixedArray is faster than Array
Reading performance: 50/50, after many tests, the Array reading speed is even faster
If you can determine that you only need to use the index array, and can predict the number of members of the array, It is obviously more suitable to use SplFixedArray.
The above is the detailed content of Array and SplFixedArray comparison (code example). For more information, please follow other related articles on the PHP Chinese website!