简体   繁体   English

空向量与双端队列的保留时间复杂度以及使用emplace还是push_back

[英]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. 我正在辩论哪种方法会更快,如果我使用数据结构将回调存储在类中,那么我应该使用向量并在启动时保留,还是在这种情况下仅使用双端队列,因为用户总数尚不知道,但是大约15左右。我想这两种情况下,每次分配与要在我的班级中抢占先机相比有何取舍?

#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 push_backemplace_back此处链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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