Looking at the Pimple source code I found that it is storing objects and their ids in two different arrays:
class Container implements \ArrayAccess
{
private $values = array();
...
private $keys = array();
}
And then:
public function offsetSet($id, $value)
{
...
$this->values[$id] = $value;
$this->keys[$id] = true;
}
And finally:
public function offsetGet($id)
{
if (!isset($this->keys[$id])) {
throw new \InvalidArgumentException(sprintf('Identifier "%s" is not defined.', $id));
}
}
I've also seen something similar in Phalcon source code here.
My question is why to store object id key separately, why not just if (!isset($this->values[$id]))
? Is it faster to search within an array? I did some tests and it seems that search speed is pretty the same.
Ok, it seems like when the array entry value may be null
you have to check key existence with an array_key_exists()
function. However, this is several times slower than isset()
, so having keys in the separate array makes possible to use isset()
.
But the better way would be if (isset(...) || array_key_exists(...))
, that has almost the same speed as simple isset()
, but eliminates the need of separate array for keys tracking (thanks, @doydoy44).