How do I clear the std::queue efficiently?

后端 未结 11 972
醉梦人生
醉梦人生 2020-12-12 09:10

I am using std::queue for implementing JobQueue class. ( Basically this class process each job in FIFO manner). In one scenario, I want to clear the queue in one shot( delet

11条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-12 09:26

    Apparently, there are two most obvious ways to clear std::queue: swapping with empty object and assignment to empty object.

    I would suggest using assignment because it simply faster, more readable, and unambiguous.

    I measured performance using following simple code and I found that swapping in C++03 version works 70-80% slower than assignment to an empty object. In C++11 there is no difference in performance, however. Anyway, I would go with assignment.

    #include 
    #include 
    #include 
    #include 
    #include 
    
    int main()
    {
        std::cout << "Started" << std::endl;
    
        std::queue q;
    
        for (int i = 0; i < 10000; ++i)
        {
            q.push(i);
        }
    
        std::vector > queues(10000, q);
    
        const std::clock_t begin = std::clock();
    
        for (std::vector::size_type i = 0; i < queues.size(); ++i)
        {
            // OK in all versions
            queues[i] = std::queue();
    
            // OK since C++11
            // std::queue().swap(queues[i]);
    
            // OK before C++11 but slow
            // std::queue empty;
            // std::swap(empty, queues[i]);
        }
    
        const double elapsed = double(clock() - begin) / CLOCKS_PER_SEC;
    
        std::cout << elapsed << std::endl;
    
        return 0;
    }
    

提交回复
热议问题