duanrenzou1619 2015-09-09 15:18
浏览 22
已采纳

Pimple源代码:为什么将对象id和对象本身存储在不同的数组中?

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.

  • 写回答

1条回答 默认 最新

  • duanpiyao2734 2015-09-10 08:28
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 统计大规模图中的完全子图问题
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 经gamit解算的cors站数据再经globk网平差得到的坐标做形变分析
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式