which results in a chain of if's that aren't particularly optimal if there's a lot of cases to wade through.
If the cases are serialized eg 0 to n, a jump table is a better option with O(1) worst case vs O(n) for selects worse case.
though any performance increase will likely be negligible in general useage.
This works on linux x64 and probably on x86 with fasm but I don't know if it'll work on OSX or Windows x64
Edit: changed to using lea and using a datasection
Code: Select all
Macro JumpTable(table)
DataSection
! table :
EndMacro
CompilerIf #PB_Compiler_Processor = #PB_Processor_x86
Macro JumpTableData
!dd
EndMacro
CompilerElse
Macro JumpTableData
!dq
EndMacro
CompilerEndIf
Macro Switch(table,switch)
EndDataSection
EnableASM
CompilerIf #PB_Compiler_Processor = #PB_Processor_x86
mov eax, switch
jmp dword [ table + eax * 4]
CompilerElse
lea rdx, [ table ]
mov rax, switch
jmp qword [rdx + rax * 8]
CompilerEndIf
DisableASM
EndMacro
Macro caseJT(label,endlabel)
!jmp endlabel
! label :
EndMacro
Macro EndJumpTable(label)
! label :
EndMacro
Procedure foo(a.i)
Protected result
JumpTable(jmp_table_foo) ;define a jumptable
JumpTableData le,l1,l2,l3 ;set the labels 0 offset
Switch(jmp_table_foo,a) ;switch the table with the index
caseJT(l1,le)
result = a * 10
caseJT(l2,le)
result = a * 20
casejt(l3,le)
result = a * 30
EndJumpTable(le)
ProcedureReturn result
EndProcedure
Debug foo(2) ;should return 40