Dispatching on a variant
Jeremie Pelletier
jeremiep at gmail.com
Sat Sep 26 20:16:56 PDT 2009
Christopher Wright wrote:
> Justin Johansson wrote:
>> I've had a good poke around the forums and couldn't find anything on
>> this so ...
>>
>> What's the recommended method for dispatching code off the runtime
>> type of a variant variable
>> (Phobos D2 std.variant)?
>>
>> Does one use a bunch of
>>
>> if ( var.peek!(type1)) { ... }
>> else if ( var.peek!(type2) { ... }
>>
>> for all N possible types, or is there a better & faster way with a
>> switch or jump table of sorts?
>
> Variant should have an accessible typeinfo property. (When I say should,
> I mean that it would be appropriate for it to have it. I am not saying
> that I believe it has it.) It should be faster to compare that (or
> switch on typeinfo.name) than to peek for each type.
I wouldn't make that rely on string switch. While it's a very convenient
feature to have in D that's usually only seen in scripting, its also a
*slow* one when compared to integral switch.
string switch actually walks the case strings and compares with the
source string until it finds a match, a binary search is much faster if
you don't care about the order of the tests.
Also if someone strips his executable from all names in TypeInfo and
ClassInfo to prevent people from peeking into his internals, it breaks
the code. Some companies out there goes to great lengths to make their
executables as hard to reverse engineer as possible.
A good alternative would be for the algebraic type to define an internal
enum which is used for switch statements:
alias Algebraic!(int, void*, Object) MyType;
switch(myType.typeId) {
case MyType.INT:
case MyType.VOIDPTR:
case MyType.OBJECT:
}
While not perfect it definitely is fast.
More information about the Digitalmars-d
mailing list