0

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 
R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
bjackfly
  • 3,236
  • 2
  • 25
  • 38
  • 3
    15 is tiny. It's unlikely you'll be able to measure any difference at all between using either container with `push_back` or `emplace`. – Yuushi Jul 09 '13 at 05:55
  • 2
    `__Pricer_hpp__` is a [reserved name](http://stackoverflow.com/a/228797/981959), stop using it – Jonathan Wakely Jul 09 '13 at 10:06
  • thanks for the heads up on reserved names. It seems any _[a-zA-Z] shouldn't be used as the standard can reserve those as well with the capital letters being worse, also it seems _t suffix shouldn't be used if you use POSIX. How do you name your private vars with an underbar after the name ? – bjackfly Jul 09 '13 at 19:07

1 Answers1

4

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

Community
  • 1
  • 1
fen
  • 9,835
  • 5
  • 34
  • 57
  • makes sense. thanks for the info, I was thinking about in the future where you might have say 100+ clients but I agree it is probably fine to just use a vector in this case. What about the emplace_back vs. push_back part of the question? – bjackfly Jul 09 '13 at 18:41
  • 1
    100 is still quite a small number :) – fen Jul 09 '13 at 19:40