3 ms·
Is it just me, or for this example does the "dispatch table" seem way more complex (and likely less efficient) than the switch statement? The original is not di
by obeattie 13y ago
Is it just me, or for this example does the "dispatch table" seem way more complex (and likely less efficient) than the switch statement? The original is not difficult at all to interpret.
- taf2 13y agoIt depends, sometimes if you have a few different context e.g. multiple click handlers that are being bound in different contexts of your app, that a table makes a lot more sense then repeating the switch or even wrapping the switch in a function...
- bjourne 13y agoYes it is just you. :) The original becomes horrible when the number of cases grows, when you want a default and can introduce subtle bugs if you forget a break. In the second example, there is a clean separation between processing commands and dispatching on the input. For example, you might want to extend processUserInput with "invalid command" handling, commands with arguments or even add commandTable as an argument to it so that you can reuse it for all your dispatching needs. And to top it of, you can dynamically add new commands to the dispatch table which you can't to a switch.
- artificialidiot 13y agoI'd like to see you hunt for the dynamically added case to the dispatch table. Maybe then, you'll change your mind. There is no fundamental difference between either approaches except the runtime cost. If you need conditonals, use them. If you need a lookup table, use them. Keep the code predictable.
- nahname 13y agoThe dispatch table is shorter than the switch, so there is a lot less noise. The invocation is a little clever, but overall I would consider them about equally complex. Maybe you meant unconventional? The performance is substantially different. The dispatch table is ~75% slower (in chrome). http://jsperf.com/switchvsdispatchtable http://jsperf.com/switchvsdispatchtable One thing I really like about dispatch tables is that it forces the developer to only be able to handle the decision logic. The number of times I've had to cleanup a switch with 20-30 lines under each condition (sometimes including another switch) is too many to count.
- drgath 13y ago> The performance is substantially different. The dispatch table is ~75% slower (in chrome). Of course those are, they're doing very different things in that test case. Your first case is just returning a value, and the second is executing a function to return a value. Here's a better comparison, http://jsperf.com/switchvsdispatchtable/2 http://jsperf.com/switchvsdispatchtable/2 There's nothing inherently slow about dispatch tables, it all about how you implement them. As someone else mentioned, the OP should be using bind to reduce the # of function calls instead of executing a function which executes a function.
- deleted 13y ago[deleted]