(August 17, 2022 at 3:08 pm)HappySkeptic Wrote:(August 17, 2022 at 2:02 pm)FlatAssembler Wrote: As somebody who has made a compiler for his programming language, I would expect compilers to output the same code for switch-case and if-else. Think of it this way, the way to translate this:
to assembly code is this:Code:var codebyte = currentDirective & 0xff000;
switch (codebyte){
case 0x00000:
//Call a Register load from register function here.
break;
case 0x01000:
//Call a Register load from value function here.
break;
}
The compiler does not benefit from knowing the variable codebyte is the same at both Point #1 and Point #2.Code:mov eax, dword ptr [currentDirective]
and eax, 0xff000
mov dword ptr [codebyte], eax
cmp dword ptr [codebyte], 0x00000 # Point #1
jnz label0
#Call a Register load from register function here.
label0:
cmp dword ptr [codebyte], 0x01000 # Point #2
jnz label1
#Call a Register load from value function here.
label1:
In .NET, if the switch statement has more than 5 elements, it changes to using a jump table, instead of nested if's (this is from Microsoft's documentation).
In C++ the compiler is free to do whatever the heck it wants.
Do you ever wonder why switch statements in most languages are only for enumberable types (enum or integer)? It is so one can create a jump table or map in situations where that gives better performance.
What's a "jump table"? Can JavaScript do that, since it allows strings to be used in switch statements?