Reputation: 79
I was playing with some code and I wrote this little class to pool std::wstring. As I profile it I'd like to know your oppinion about approaching a pool of strings this simple.
I have a std::vector of std::wstring and two maps, one for holding the indexes of the unused elements in the vector and another for the ones that are being used.
If a string is requested with new_string() and there isn't any free indexes left, I resize the vector and insert the newly added indexes to the free indexes map.
Here is the code:
typedef std::wstring string_t;
class string_pool
{
public:
string_pool()
{
grow_factor = 2;
strings.resize(10);
for (size_t i=0; i<10; i++)
{
free_indexes.insert(std::make_pair(&strings[i],i));
}
}
virtual ~string_pool()
{
}
string_t* new_string()
{
if (!free_indexes.size())
{
size_t old_size = strings.size();
size_t new_size = old_size+grow_factor;
for (size_t i=old_size;i<new_size; i++)
{
free_indexes.insert(std::make_pair(&strings[i],i));
}
strings.resize(new_size);
}
iter = free_indexes.begin();
used_indexes.insert(*iter); // Mark the index as used
string_t* str = (*iter).first; // Get a pointer to the string
free_indexes.erase(iter); // Erase the free index
return str;
}
void delete_string(string_t* str)
{
str->clear();
iter = used_indexes.find(str);
free_indexes.insert(*iter); // Mark the index as free
used_indexes.erase(iter); // Erase the used index
}
protected:
std::map<string_t*, size_t> used_indexes;
std::map<string_t*, size_t> free_indexes;
std::vector<string_t> strings;
size_t grow_factor;
std::map<string_t*, size_t>::iterator iter;
};
Upvotes: 0
Views: 141
Reputation: 283793
The new
/delete
you care about is not allocation of the string
descriptors, but the string
data. Pooling string
objects doesn't help much, the content will still be dynamically allocated.
Upvotes: 4