I ran the tests out of curiosity using Java 11 and jmh looking at throughput...
Three implementation, if else if..., map (hashmap) and a switch.
With one notable exception, the results were as I had expected:
The if else if... approach became slower for matches against the "later" input options i.e. proportional to the number of comparisons performed before a match was found.
The map approach provided constant performance for all input options,
The switch approach also provided constant performance for all input options, not expected but I'll assume some compiler optimisations there.
The switch approach was slightly faster than the map approach.
The switch and map approaches were both slower than the if else if...until you test the 3rd or 4th input options respectively.
The if else if... approach degraded in performance until the 11th input when it improved slightly and then continued to degrade again. (I can't explain this).
In general, I prefer the map approach over a large if else if... block and 3 or 4 branches seems like a nice rule of thumb for when you might want to look at moving to the map or switch approach, both in terms of performance and readability, IMHO.
I ran the tests out of curiosity using Java 11 and jmh looking at throughput...
Three implementation,
if else if...
,map
(hashmap) and aswitch
.With one notable exception, the results were as I had expected:
if else if...
approach became slower for matches against the "later" input options i.e. proportional to the number of comparisons performed before a match was found.map
approach provided constant performance for all input options,switch
approach also provided constant performance for all input options, not expected but I'll assume some compiler optimisations there.switch
approach was slightly faster than themap
approach.switch
andmap
approaches were both slower than theif else if...
until you test the 3rd or 4th input options respectively.if else if...
approach degraded in performance until the 11th input when it improved slightly and then continued to degrade again. (I can't explain this).In general, I prefer the
map
approach over a largeif else if...
block and 3 or 4 branches seems like a nice rule of thumb for when you might want to look at moving to themap
orswitch
approach, both in terms of performance and readability, IMHO.