Does really SplFixedArray perform better than arrays?

不羁的心 提交于 2019-12-03 03:33:54

As illustrated by the benchmarks performed by the author of this article:

One can conclude that the memory footprint of SplFixedArray is indeed smaller, but noticeable only for a large amount of array elements. Because SplFixedArray is technically an instance of a class aswell, as opposed to traditional arrays, that is what is causing small arrays to be actually sightly more memory consuming if implemented by SplFixedArray, but as this extra few hundred of bytes remains constant, it becomes irrelevant as the size of the array grows.

Side note: don't micro-optimize, not every hammer is created for every nail. SplFixedArray is there for extreme cases, e.g. for arrays of hundreds of thousands of elements, where cutting down a few bytes of memory usage per element has a large impact on the overall memory usage; but don't bother using it unless you are really sure your array is or could be a potential bottleneck of the application.

periklis

A SplFixedArray is supposed to be faster than arrays. It doesn't say anything about memory consumption (which is what you're testing here). From http://php.net/manual/en/class.splfixedarray.php:

"The main differences between a SplFixedArray and a normal PHP array is that the SplFixedArray is of fixed length and allows only integers within the range as indexes. The advantage is that it allows a faster array implementation"

However, using an array of 100000 entries, reveals that it also uses less RAM:

$users = array();
for ($i=0;$i<100000;$i++) { 
    $users[$i] = array('id' => rand(), 'name' => 'default');
}
echo memory_get_peak_usage(true); //returns 31457280

$users = new SplFixedArray(100000);
for ($i=0;$i<100000;$i++) { 
    $users[$i] = array('id' => rand(),
            'name' => 'default');
}
echo memory_get_peak_usage(true); //return 26738688

yes if you are using them with a fixed size.

If you are constantly changing the size for each new element to add could be slower and it it might not be the wrong usage too.

It is faster due to the implementation of array in PHP that those are not real array as a per definition in programming languages, but are instead associative array, implemented with a Hash table. (so array in PHP are basically Hash Tables)

Whilst the SplFixedArray is implemented using the "malloc" of C as a almost normal C array, of course wrapped in a small struct to keep track and manipulate the array as a per use cases.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!