Baykal
Baykal

Reputation: 569

Which one is faster? A class function or a function with class pointer?

In my program I am using several classes and tons of functions with(in) them. I would like to know which one of the would work faster or there is no difference in between them in terms of speed.

1st: Class function

class mex{
  public:
    int length,nof_evaluations,nof_fast_evaluations;
    tree T;
    calc_mex(vector<string>,vector<double>);
}; 

which will be called by

mex m;
vector<string> v1;
vector<double> v2;
m.calc_mex(v1,v2);

2nd: Function with class pointer

class mex{
  public:
    int length,nof_evaluations,nof_fast_evaluations;
    tree T;
}; 
calc_mex(mex*,vector<string>,vector<double>);

which will be called by

mex m,*mptr;
mptr=&m;
vector<string> v1;
vector<double> v2;
calc_mex(mptr,v1,v2);

I am using both of the ways in my program, but more inclined to way 1 since it looks cleaner and better organized. I am also calling these type of functions 100K times in a single run of the program. So I am wondering if any of them will work better timing wise.

Thanks!

Upvotes: 1

Views: 569

Answers (3)

bstamour
bstamour

Reputation: 7766

In C++ all member functions (unless they're virtual) are freestanding functions with "this" passed in as the first argument. You won't get any speed gains from choosing one over the other, they're both just function calls.

Upvotes: 1

Gnosophilon
Gnosophilon

Reputation: 1369

I second the answer given by Alok save and I have to reiterate a statement from Donald Knuth (he's famous, so the statement must be true, obviously...):

Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.

My two cents on this issue: Measure something until you are very sure that your "optimization" will benefit the program. Otherwise, you tend to produce code that becomes more unreadable and unmaintainable as time progresses...

Upvotes: 3

Alok Save
Alok Save

Reputation: 206508

Rather than speed the deciding factor should be whether the function logically belongs to the class or not. If yes make it a member. If not make it a free standing function.

BTW each member function is implicitly passed an this pointer so there is not much difference between the two versions. If you are truly concerned about performance. Make a sample program with both versions and profile it in your environment with a large data set.

Upvotes: 5

Related Questions