C++ STL Map vs Vector speed

后端 未结 12 1051
日久生厌
日久生厌 2020-12-16 11:56

In the interpreter for my experimental programming language I have a symbol table. Each symbol consists of a name and a value (the value can be e.g.: of type string, int, fu

12条回答
  •  时光取名叫无心
    2020-12-16 12:22

    You effectively have a number of alternatives.

    Libraries exist:

    • Loki::AssocVector: the interface of a map implemented over a vector of pairs, faster than a map for small or frozen sets because of cache locality.
    • Boost.MultiIndex: provides both List with fast lookup and an example of implementing a MRU List (Most Recently Used) which caches the last accessed elements.

    Critics

    • Map look up and retrieval take O(log N), but the items may be scattered throughout the memory, thus not playing well with caching strategies.
    • Vector are more cache friendly, however unless you sort it you'll have O(N) performance on find, is it acceptable ?
    • Why not using a unordered_map ? They provide O(1) lookup and retrieval (though the constant may be high) and are certainly suited to this task. If you have a look at Wikipedia's article on Hash Tables you'll realize that there are many strategies available and you can certainly pick one that will suit your particular usage pattern.

提交回复
热议问题