开发者

Storing elements in an unordered_set vs storing them in an unordered_map

Suppose I have the following User struct:

struct User { 
    string userId; 
    UserType userType; // UserType is just an enumeration
    string hostName;
    string ipAddress;
    //and more other attributes will be added here

};

and I need to store a collection of user records (around 10^5 users, can scale higher too ). Would it be better in performance if I store it as an unordered_set or unordered_map? Unordered_set is technically the same as HashSet, and unordered_map is the same as HashMap, right? Using a regular set (ordered) is not an option, as insertion and deletion will get very slow when the number of elemen开发者_C百科ts increase.

unordered_set <User> userRecords;

OR

unordered_map <string, User> userRecords; // string is the user ID.

I need it to be very fast in terms of insertion, deletion, and to access a particular user object by its userId.


I would choose unordered_map, because I can get a user, given a userid at any time, without any extra work, while with unordered_set I don't have this facility.

As for the mentioned operations, the speed will be almost same.


Since the unordered_set<> doesn't give you the possibility to easily access a user by his userId, unordered_map<> seems to be the correct choice.


If performance is a significant concern then you'll probably want to profile and see which one performs better. Otherwise, choose the one that most logically describes what you're trying to do. [With only 100K items I think set and map may yet have acceptable performance if you need ordering somewhere else]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜