简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM