How are switches optimized

IntegratedDimensions IntegratedDimensions at gmail.com
Fri Jun 1 21:18:25 UTC 2018


What is the best optimizations that a compiler does to switches 
in general and in the D compilers?

A switch can be seen as if statements, or safer, nested if elses.

but surely the cost per case does not grow with depth in the 
switch? If one has a switch of N case then the last cost surely 
does not cost N times the cost of the first, approximately? This 
is the cost when implementing a switch as nested ifs.

Tables can be used to give O(1) cost, are these used in D's 
compilers? How are they generally implemented? Hash tables? If 
the switch is on an enum of small values is it optimized for a 
simple calculating offset table?

switch(e)
{
    case E.a:
    ...
    case E.z:
    ...
}

jmp offset + val(e)

Or, in general a map table can be used

jmp offset + map[e]


Just curious...



More information about the Digitalmars-d-learn mailing list