Question

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 
Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top