简体   繁体   中英

time complexity of reserve on an empty vector vs. a deque and whether to use emplace or push_back

I am debating which is going to be faster, if I am using a data structure to store call backs within a class should I use a vector and reserve on start up or should I just use a deque in this case since the total number of subscribers is not known but will be relatively small say around 15. I guess what is the trade off in these two scenarios allocating each time versus taking the hit to reserve up front in my class.

#ifndef __Pricer_hpp__
#define __Pricer_hpp__

#include <utility>
#include <vector>

class Pricer
{
  public: 
    typedef  void (*callback_fn)(double price, void *subscription);

    Pricer(): _initialSubscriberNum(15), _callbacks() { _callbacks.reserve(_initialSubscriberNum); }  // is it better to use a deuqe and remove the need for the reserve?

    void attach (const callback_fn& fn, void *subscription )
    {
      _callbacks.emplace_back(fn,subscription); // is emplace_back better than using push_back with std::pair construction which I am assuming would do a move version of push_back?  
    }

    void broadcast(double price)
    {
      for ( auto callback : _callbacks)
      {
        (*callback.first)(price, callback.second);
      }
    }

  private:
    typedef std::pair<callback_fn, void *> _callback_t;
    const unsigned int _initialSubscriberNum;
    std::vector<_callback_t> _callbacks; // should this be a deque?
};

#endif 

general suggestion is to use a vector and then if you have some performance problems (which in your cases will not happen probably) change to some other data structure.

Remember about "premature optimization" that sometimes can hurt.

push_back vs emplace_back : link here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM