How to optimize such simple data (event) casting Class?
So I have created compilable prototype for a graph element that can cast its data to subscribed functions.
//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();
}
开发者_如何转开发
Is it possible to optimize my data casting system? And if yes how to do it?
- Implement the program correctly and safely
- If performance Not Acceptable
- While Not Acceptable
- Profile
- Optimize
- While Not Acceptable
- Done!
In my experience, premature optimization is the devil.
EDIT:
Apparently while I was formatting my answer, another James ninja'd me with a similar answer. Well played.
Is it possible to optimize my data casting system? And if yes how to do it?
If your program is not too slow then there is no need to perform optimizations. If it is too slow, then generally, improving its performance should be done like so:
- Profile your program
- Identify the parts of your program that are the most expensive
- Select from the parts found in step 2 those that are likely to be (relatively) easy to improve
- Improve those parts of the code via refactoring, rewriting, or other techniques of your choosing
Repeat these steps until your program is no longer too slow.
精彩评论