r/tinycode • u/Elbynerual • Jun 20 '18
What's the best substitution for a switch statement to make it smaller?
I'm writing something simple and it's going to have a switch statement with like 8 or 10 cases. Switch statements feel really drawn out and wasteful to me. Is there something more efficient that can be used in their place?
13
Upvotes
16
u/merkidemis Jun 20 '18
As long as it's clear and east to read leave it. Don't chase compactness at the cost of readability.
8
u/[deleted] Jun 20 '18
If each case can be inlined so that it's just one line then that works:
7
u/garblesnarky Jun 20 '18
I like to use a map or dict for this, may or may not be shorter depending on the language, but I think it usually looks better.
5
u/Dresdenboy Jun 22 '18
How much is happening in the statements?
Source code size optimization:
v=(i>4)?(i>5)?6:5:(i<2)?0:1;
You could build some tree here.
1
u/TheAwdacityOfSoap Jun 28 '18
Can you paste your code (or example code like it)? Sometimes a switch statement is what you want. Sometimes it’s if/else blocks. Sometimes it’s a map or object containing functions. Sometimes you might move that logic into a series of subclasses and call the function directly.
3
u/cthutu Jun 20 '18
An good optimiser will convert those switch statements to be table driven if it considers it. Do not try to beat the optimiser. Just code as normal.