views:

80

answers:

2

Hello!

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.

+3  A: 

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.

Space_C0wb0y
+1  A: 

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.

Diego Sevilla
Do you mean that it would take longer to access the last of the listed types than the first? A quick test shows that this doesn't seem to be the case. Are you sure the recursion isn't compile-time?
UncleBens
UncleBens: Looking at it twice, the search is unrolled to a given limit (that for what I've seen is the actual mpl list size limit, whatever is it). Then, the call is recursive. So yes, maybe up to 10 types or so there is no recursive call, but again, as you say, nothing better than a small test.
Diego Sevilla