c++中通过结构减少Cached内存的方法

问题描述 投票:0回答:1

我一直在使用一些结构来缓存一些临时列表,并且,我想找到一些解决方案来减少分配的内存,同时保持性能。

structure LatestInfo
{
        std::string visitedWebsites;
        std::string watchedVideo;
        std::string userId;
        std::string userName;
        unsigned int lastLoginTime;
        std::string contentsRating;
        //and so on
}

而我有 std::vector<LatestInfo> latestList 储存 LatestInfo 结构。

有许多 LastestInfolatestList 而且它的体积越来越大。

因此,它在我们的系统中分配了大量的内存(超过200Mbs)。

不仅如此 LatestInfo是定期更新的(每2小时一次),但性能也很重要,我们只在DB(SQLite)中存储一些固定的值。

所以,我想在不使用DB的情况下减少其分配的内存。

IMO,如果std::string可以被压缩,那将是很好的,并且需要最小的改变。你知道一些开源或库来压缩它以减少分配的内存吗?

或者你有更好的解决方案?

谢谢你。

c++ stdvector stdstring
1个回答
1
投票

如果你的字符串有很多重复,你可以使用 "字符串内嵌",你只有一个字符串数据的副本,然后指针回到它。https:/en.wikipedia.orgwikiString_interning(字符串内嵌)

这里有一个C++库,可以帮你做到这一点(我没有用过这个库,只是在我的谷歌搜索中出现过)。https:/github.comRipcordSoftwarelibstringintern。


1
投票

我用飞重得到了一个有效的结果,解决办法很简单,如下。

#include <boost/flyweight.hpp>
structure LatestInfo
{
        flyweight<std::string> visitedWebsites;
        flyweight<std::string> watchedVideo;
        flyweight<std::string> userId;
        flyweight<std::string> userName;
        flyweight<std::string> lastLoginTime;
        flyweight<std::string> contentsRating;
        //and so on
}

std::map<unsigned int, LatestInfo> userMap;   //index per LatestInfo

更多信息,我的数据有 total 12,000 LatestInfo 并且有很多重复的字符串。

例如,特别是visitedWebsites(last),其中包含了url,平均长度约100,80%的url是重复的。 url的平均长度约为100,80%的url是重复的。

So, I save my cached memory about 1MB in url, and total 5 MB was saved after applying flyweight.

尽管Flyweight Pattern可能会使程序变慢,但我还是去掉了不必要的复制和成功等低效率的逻辑,以保持性能。

请注意,boost flyweight patterns在对象存活的时候会保持数据。

© www.soinside.com 2019 - 2024. All rights reserved.