使用Boost.bimap时如何避免密钥复制?

时间:2014-01-14 11:16:45

标签: c++ boost

using Boost.bimap for implementing a LRU cache包含一些包含字符串的复杂密钥

问题是每次调用find()时都会复制密钥。我想避免这种不必要的副本(一般来说:尽可能少地制作字符串的副本,也许是通过模板?)

最小测试用例(带gist version):

#include <string>
#include <iostream>

#include <boost/bimap.hpp>
#include <boost/bimap/list_of.hpp>
#include <boost/bimap/set_of.hpp>

class Test
{
public:
    struct ComplexKey
    {
        std::string text;
        int dummy;

        ComplexKey(const std::string &text, int dummy) : text(text), dummy(dummy) {}

        ~ComplexKey()
        {
            std::cout << "~ComplexKey " << (void*)this << " " << text << std::endl;
        }

        bool operator<(const ComplexKey &rhs) const
        {
            return tie(text, dummy) < tie(rhs.text, rhs.dummy);
        }
    };

    typedef boost::bimaps::bimap<
    boost::bimaps::set_of<ComplexKey>,
    boost::bimaps::list_of<std::string>
    > container_type;

    container_type cache;

    void run()
    {
        getValue("foo", 123); // 3 COPIES OF text
        getValue("bar", 456); // 3 COPIES OF text
        getValue("foo", 123); // 2 COPIES OF text
    }

    std::string getValue(const std::string &text, int dummy)
    {
        const ComplexKey key(text, dummy); // COPY #1 OF text
        auto it = cache.left.find(key); // COPY #2 OF text (BECAUSE key IS COPIED)

        if (it != cache.left.end())
        {
            return it->second;
        }
        else
        {
            auto value = std::to_string(text.size()) + "." + std::to_string(dummy); // WHATEVER...
            cache.insert(typename container_type::value_type(key, value)); // COPY #3 OF text

            return value;
        }
    }
};

1 个答案:

答案 0 :(得分:1)

Bimap没有直接使用std:map(我之所以这样说是因为你使用的是set_of),而是通过不同的容器适配器创建视图,并且在此过程中复制了密钥。根据你在问题中定义bimap的方式,不可能显着提高性能。

要获得bimap相对于 ComplexKey 的更好性能,您宁愿存储指向 ComplexKey 的指针(最好是原始的;没有隐含的密钥的所有权) bimap)并提供您自己的分拣机。指针复制起来很便宜,缺点是你必须与地图并行管理密钥的生命周期。

做一些事情,

std::vector<unique_ptr<ComplexKey>> ComplexKeyOwningContainer;
typedef boost::bimaps::bimap<
    boost::bimaps::set_of<ComplexKey*, ComplexKeyPtrSorter>,
    boost::bimaps::list_of<std::string>
    > container_type;

请注意,如果您在演出后还需要注意{b}的另一面std::string。它们可能非常昂贵,临时性很常见,并且它们会遇到与 ComplexKey 键相同的问题。