2012-03-07 39 views
1

我想實現這個:http://lynxline.com/stack-vs-heap-pimpl-performance/與一個特定的對象,這將創建多次,並需要儘可能快。然而,在我的對象中,我有QTimers連接插槽,直到構造函數之後才啓動。我可以在QTimers和信號中使用C++對象創建優化嗎?

我的問題這個方法仍然適用於QTimer()和他們各自的信號和插槽?還是僅限於沒有實例化其他對象的對象?

這是優化例如:

template <int def,int real> 
struct check_d_size : ::static_assert::is_fail<(bool)(def == real)> {}; 

class StackObj { 
public: 
    StackObj() { 
     check_d_size<d_size,sizeof(Private)>(); 
     d = new(d_bytes) Private; 
    } 
    virtual ~StackObj() { d->~Private(); } 

private: 
    class Private { 
    public: 
     inline void * operator new(size_t, quint8 * mem) { return mem; } 

     int i; 
     int j; 
     DynObj * p; 
     std::string str; 

     class Check { 
     public: Check() { static bool b=true; if (b) { qDebug() << "ok new stack"; b = !b; } } 
       ~Check() { static bool b=true; if (b) { qDebug() << "ok del stack"; b = !b; } } 
     } chk; 
    }; 
    Private * d; 
    static const int d_size = 32; 
    quint8 d_bytes[d_size]; 
}; 

這是我的構造函數:

PenPathDetails::PenPathDetails(DiagramScene *parent, int penId) : 
    m_parent(parent), 
    m_penId(penId), 
    m_originalPenId(-1) 
{ 
    m_AutoJoinTimer = new QTimer(); 
    m_AutoJoinTimer->setSingleShot(true); 
    m_MouseLastMovedTimer = new QTimer(); 
    m_MouseLastMovedTimer->setSingleShot(true); 

    connect(m_AutoJoinTimer, SIGNAL(timeout()), this, SLOT(slotGroupPaths())); 
    connect(m_MouseLastMovedTimer, SIGNAL(timeout()), this, SLOT(slotMouseReleased())); 

    reset(); 
    resetOriginalPenId(); 
} 
+0

我沒有看到您的StackObj和PenPathDetails :: PenPathDetails之間的關係。或者我錯過了什麼? – Koying 2012-03-07 15:13:07

+0

順便說一句,感謝您的鏈接。非常有趣... – Koying 2012-03-07 15:30:24

+0

Koying,現在沒有關係,我想讓PenPathDetails使用與StackObj相同的創建方法。 – 2012-03-07 15:51:22

回答

2

當你做你的私有類的內存分配優化情況。 無論你在哪裏分配它,它都會更快,因爲它分配在堆棧而不是堆上。

假設PenPathDetails是你的私人類,它的分配速度會更快,QTimer的分配將保持不變,除非你在棧上分配你的QTimer,也就是QTimer m_AutoJoinTimer而不是QTimer* m_AutoJoinTimer

相關問題