Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - boost get question

Does someone know if the boost::get for the boost::variant is a performance-consuming operation or not.

Right now I am refactoring some old code in a performance-critical part, where "varianting" was implementing by containers for each possible types and corresponding enum.

Obviously, this is fast, but ugly and right now when I have to refactor the code so that it would work with one more type, I want to get rid of that old part of code and replace it with boost::variant.

Also, I can't simple "profile both variants and compare" because this refactoring is a pain in the ass and would be pretty time consuming.

So, if someone knows how does boost::get<x> performs comparing to generic enum-based type dispatching, I would appreciate if you share this knowledge.

There is another variant of using boost::variant<types> with custom visitor (as described in boost::variant documentation) - may this be faster than boost::get in my case?

Thank you.

like image 570
Yippie-Ki-Yay Avatar asked Oct 22 '10 13:10

Yippie-Ki-Yay


2 Answers

You could still write a simple test-application to compare the two, it doesn't have to be the production environment.

A colleague of mine had a similar problem to this one recently. In his scenario there where objects of different types, but he always knew beforehand which type he expected. Also his data-structure was huge, so memory was an issue. He solved the problem by using void * and reinterpret_cast. This prevents the memory-overhead of polymorphism and is very fast. You have to be absolutely sure of what you are doing though, otherwise things will explode.

like image 67
Björn Pollex Avatar answered Oct 26 '22 23:10

Björn Pollex


Looking at the code, get<> is implemented using the internal visitor mechanism of the boost::variant. In turn, the visitor mechanism relies on mpl sequences, and it is executed step by step. That means at most n steps on an n type variant, but the loop (recursive call) is there. Again, as Space Cowboy suggests, a small performance test would be helpful.

like image 20
Diego Sevilla Avatar answered Oct 27 '22 00:10

Diego Sevilla