I have a command list includes hundreds of commands, and this command list needs to be called frequently. like:
if([command isEqualToString:"openPage1"]){
open page 1
}else if ([command isEqualToString:"jumpToPage4"]){
get param1 and param2
jump to page 4
}else if ([command isEqualToString:"backToPage10"]){
get param1
back to page 10
}....
Since there are hundreds of commands and called frequently, so I don’t think “if else” is a good way…
Which algorithm is faster and efficiency?
You could have an
NSDictionarythat maps the command names directly to code, be it selectors, invocations or blocks. Something like:And then:
Of course the dictionary would be initialized just once and then cached. If the action is always the same call, just with different arguments, you can map the command names directly to the arguments:
And there’s also the option of just parsing the command name to extract the page number, if that’s possible.
PS. Starting with LLVM 4.1 (?) you can also use the shorthand literal syntax to create the action dictionary, which makes it a bit easier on the eyes:
Note that even the trailing comma after the second command block works.