Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pimple source code: Why to store object id and object itself in different arrays?

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.

like image 375
Kanstantsin K. Avatar asked Sep 09 '15 15:09

Kanstantsin K.


1 Answers

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).

like image 186
Kanstantsin K. Avatar answered Sep 19 '22 04:09

Kanstantsin K.