Tuesday, November 24, 2009

Are templates faster than subclasses?

Are template classes faster than using a derived class? Intuition would tell me that the template class should be faster. However to test if this is the case I wrote the following small programs:

Subclassed version:

#include <iostream>

using namespace std;

class mybaseclass {
public:

virtual int get_i() = 0;
};

class myclass : public mybaseclass {

public:

myclass(int in) {
i=in;
}

int get_i() {
return i;
}

int i;
};

class otherclass : public mybaseclass {

public:

otherclass(int in) {
i = in;
}

int get_i() {
return i*i;
}

int i;
};

int main(void) {
myclass *c = new myclass(2);
long int sum=0;
for(size_t n=0;n<2000000000;n++) {
mybaseclass *cc = c;

sum += cc->get_i();

}
cout << sum << endl;
delete c;
}



Templated version:
#include <iostream>

using namespace std;

template<class t>
class myclass {

public:

myclass(int in) {
i=in;
}

int get_i() {
return i;
}

int i;
};

template<class t>
class otherclass {

public:

otherclass(int in) {
i = in;
}

int get_i() {
return i*i;
}

int i;
};

int main(void) {
myclass<int> *c = new myclass<int>(2);

long int sum=0;
for(size_t n=0;n<2000000000;n++) {

sum += c->get_i();

}
cout << sum << endl;
delete c;
}




$g++ small_templateclassed.cpp -O3;time ./a.out
4000000000

real 0m0.008s
user 0m0.000s
sys 0m0.001s


$ g++ small_classed.cpp -O3;time ./a.out
4000000000

real 0m5.908s
user 0m5.853s
sys 0m0.018s

My first effort was IO bound, but in this case it appears that templatized code is substantially faster.

Nabble thread is here.

No comments: