I have been following design patterns for a while and came to know that dispatching call to methods dynamically by declaring them as virtual is costly due to all the VTable referencing stuffs. So if a method is heavily used, we should avoid declaring them virtual. CRTP (Curiously recurring template pattern) can be used to avoid performance drop.
To check on how much performance gain does CRTP provide, I wrote two versions of a simple class hierarchy. One with virtual methods and other using CRTP. In order to see clear perf boost, I called a method 1000 times. To my surprise, CRTP code took more time than the one with virtual method. I tried to run code more than once and got the same result.
Code with virtual method
Image* pImage = new TiffImage;
auto t1 = Clock::now();
LOOP(1000)
pImage->Draw();
auto t2 = Clock::now();
cout << "Delta t2-t1: "
<< std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1).count()
<< " nanoseconds" << endl;
Time taken: 6938221 nanoseconds
Code with CRTP
Image<TiffImage>* pImage = new TiffImage;
auto t1 = Clock::now();
LOOP(1000)
pImage->Draw();
auto t2 = Clock::now();
cout << "Delta t2-t1: "
<< std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1).count()
<< " nanoseconds" << std::endl;
Time taken: 7045868 nanoseconds
Questions:
- Does CRTP boost performance as it is described in theory?
- As above results are from ideone, will the result change with compiler?
Aucun commentaire:
Enregistrer un commentaire