Created
January 14, 2014 10:54
-
-
Save arielm/8416549 to your computer and use it in GitHub Desktop.
I'm using Boost.bimap for implementing a LRU cache with some "complex key" containing a string. The problem is that the key is copied every-time I'm invoking find(). I would like to avoid this un-necessary copy (and in general: make as few as possible copies of the string, maybe via templates?)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment