Associative Array versus SplObjectStorage
You shouldn't see the SplObjectStorage
as a key-value store, but merely a set of objects. Something is in the set or not, but its position is not important.
The "key" of an element in the SplObjectStorage
is in fact the hash of the object. It makes it that it is not possible to add multiple copies of the same object instance to an SplObjectStorage
, so you don't have to check if a copy already exists before adding.
However, in PHP 5.4
there is a new method called getHash()
which you can override that will return the "hash" of the object. This - in a sense - returns/set the key so you can allow it to store under different conditions.
The main advantage of SplObjectStorage
is the fact that you gain lots of methods for dealing and interacting with different sets (contains()
, removeAll()
, removeAllExcept()
etc). Its speed is marginally better, but the memory usage is worse than normal PHP arrays.
Results after running this benchmark with 10,000 iterations on PHP 5.6.13:
Type | Time to fill | Time to check | Memory |
---|---|---|---|
SplObjectStorage | 0.021285057068 | 0.019490000000 | 2131984 |
Array | 0.021125078201 | 0.020912000000 | 1411440 |
Array
s use 34% less memory and are about the same speed as SplObjectStorage
.
Results with PHP 7.4.27:
Type | Time to fill | Time to check | Memory |
---|---|---|---|
SplObjectStorage | 0.019295692444 | 0.016039848328 | 848384 |
Array | 0.024008750916 | 0.022011756897 | 3215416 |
Array
s use 3.8 times more memory and are 24% slower than SplObjectStorage
.
Results with PHP 8.1.1:
Type | Time to fill | Time to check | Memory |
---|---|---|---|
SplObjectStorage | 0.009704589844 | 0.003775596619 | 768384 |
Array | 0.014604568481 | 0.012760162354 | 3215416 |
Array
s use 4.2 times more memory and are 50% slower than SplObjectStorage
.