Fastest container or algorithm for unique reusable ids in C++

前端 未结 8 872
暗喜
暗喜 2021-02-04 10:33

I have a need for unique reusable ids. The user can choose his own ids or he can ask for a free one. The API is basically

class IdManager {
public:
  int Allocat         


        
8条回答
  •  再見小時候
    2021-02-04 11:03

    It would be good to know how many ids you're supposed to keep track of. If there's only a hundred or so, a simple set would do, with linear traversal to get a new id. If it's more like a few thousands, then of course the linear traversal will become a performance killer, especially considering the cache unfriendliness of the set.

    Personally, I would go for the following:

    • set, which helps keeping track of the ids easily O(log N)
    • proposing the new id as the current maximum + 1... O(1)

    If you don't allocate (in the lifetime of the application) more than max() ids, it should be fine, otherwise... use a larger type (make it unsigned, use a long or long long) that's the easiest to begin with.

    And if it does not suffice, leave me a comment and I'll edit and search for more complicated solutions. But the more complicated the book-keeping, the longer it'll take to execute in practice and the higher the chances of making a mistake.

提交回复
热议问题