簡體   English   中英

如何優化這種簡單的數據(事件)轉換類?

[英]How to optimize such simple data (event) casting Class?

因此,我為圖形元素創建了可編譯的原型,該元素可以將其數據轉換為預訂的函數。

//You can compile it with no errors.
#include <iostream>
#include <vector>

using namespace std ;

class GraphElementPrototype {

    // we should define prototype of functions that will be subscribers to our data
    typedef void FuncCharPtr ( char *) ;

public:
    //function for preparing class to work 
    void init()
    {
        sample = new char[5000];
    }
    // function for adding subscribers functions
    void add (FuncCharPtr* f)
    {
        FuncVec.push_back (f) ;
    } ;

    // function for data update
    void call()
    {
        // here would have been useful code for data update 
        //...
        castData(sample);
    } ;  

    //clean up init
    void clean()
    {
        delete[] sample;
        sample = 0;
    }

private:

    //private data object we use in "call" public class function
    char* sample;

    //Cast data to subscribers and clean up given pointer
    void castData(char * data){
        for (size_t i = 0 ; i < FuncVec.size() ; i++){
            char * dataCopy = new char[strlen(data)];
            memcpy (dataCopy,data,strlen(data));
            FuncVec[i] (dataCopy) ;}
    }

    // vector to hold subscribed functions
    vector<FuncCharPtr*> FuncVec ;

} ;


static void f0 (char * i) {  cout << "f0" << endl; delete[] i; i=0; }
static void f1 (char * i) {  cout << "f1" << endl; delete[] i; i=0; }

int main() {
    GraphElementPrototype a ;
    a.init();
    a.add (f0) ;
    a.add (f1) ;
    for (int i = 0; i<50000; i++)
    {
        a.call() ;
    }
    a.clean();
    cin.get();
}

是否可以優化我的數據投射系統? 如果是的話,該怎么做?

  • 正確,安全地實施程序
  • 如果表現不可接受
    • 雖然不可接受
      • 輪廓
      • 優化
  • 做完了!

以我的經驗,過早的優化是魔鬼。

編輯:

顯然,當我格式化答案時,另一個詹姆斯忍者給我提供了類似的答案。 打的好。

是否可以優化我的數據投射系統? 如果是的話,該怎么做?

如果您的程序不是太慢,則無需執行優化。 如果速度太慢,則通常應按以下方式進行性能改進:

  1. 分析您的程序
  2. 確定程序中最昂貴的部分
  3. 從步驟2中找到的部分中選擇可能(相對)容易改進的部分
  4. 通過重構,重寫或您選擇的其他技術來改進代碼的這些部分

重復這些步驟,直到您的程序不再太慢為止。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM