C++ - boost get question
Asked Answered
H

2

7

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.

Habsburg answered 22/10, 2010 at 13:13 Comment(3)
Have you tried looking at the source code? boost.org/doc/libs/1_44_0/boost/variant/get.hppTractor
If a custom operation were faster than their own, wouldn't they rather base their own implementation on the custom implementation??Brahmin
Did you finally go for the void*?Disengagement
D
4

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.

Dibbell answered 22/10, 2010 at 13:17 Comment(0)
E
3

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.

Ensiform answered 22/10, 2010 at 13:38 Comment(2)
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?Communalism
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.Ensiform

© 2022 - 2024 — McMap. All rights reserved.