While this is definitely premature optimization, "Mindless adherence to a quote taken badly out of context is the reason we need a high-end multi-core computer just to display a reasonably responsive GUI today" - Me.
–
Lawrence DolJan 18 '10 at 19:58

1

Knuth has a precise mind. Please note the qualifier "premature". Optimization is a perfectly valid concern. That said, a server is IO bound and the bottlenecks of network and disk I/O are orders of magnitude more significant than anything else you have going on in your server.
–
alphazeroApr 25 '11 at 2:14

8 Answers
8

That's micro optimization and premature optimization, which are evil. Rather worry about readabililty and maintainability of the code in question. If there are more than two if/else blocks glued together or its size is unpredictable, then you may highly consider a switch statement.

Alternatively, you can also grab Polymorphism. First create some interface:

public interface Action {
void execute(String input);
}

And get hold of all implementations in some Map. You can do this either statically or dynamically:

Map<String, Action> actions = new HashMap<String, Action>();

Finally replace the if/else or switch by something like this (leaving trivial checks like nullpointers aside):

actions.get(name).execute(input);

It might be microslower than if/else or switch, but the code is at least far better maintainable.

As you're talking about webapplications, you can make use of HttpServletRequest#getPathInfo() as action key (eventually write some more code to split the last part of pathinfo away in a loop until an action is found). You can find here similar answers:

If you're worrying about Java EE webapplication performance in general, then you may find this article useful as well. There are other areas which gives a much more performance gain than only (micro)optimizing the raw Java code.

I'm not so quick to dismiss all early optimization as "evil". Being too aggressive is foolish, but when faced with constructs of comparable readability choosing one known to perform better is an appropriate decision.
–
Brian KnoblauchJan 18 '10 at 14:49

7

The HashMap lookup version can easily be 10 times slower compared to a tableswitsch instruction. I wouldn't call this "microslower"!
–
x4uJan 18 '10 at 15:20

1

I'm interested in actually knowing the inner workings of Java in the general case with switch statements - I'm not interested in whether or not somebody thinks this is related to over-prioritizing early optimization. That being said, I have absolutely no idea why this answer is upvoted so much and why it is the accepted answer...this does nothing to answer the initial question.
–
searchengine27May 4 at 12:19

I wonder why this comment isn't rated higher: it is the most informitive of all of them. I mean: we all already know about premature optimalization being bad and such, no need to explain that for the 1000th time.
–
Folkert van HeusdenJul 1 '12 at 16:42

It's extremely unlikely that an if/else or a switch is going to be the source of your performance woes. If you're having performance problems, you should do a performance profiling analysis first to determine where the slow spots are. Premature optimization is the root of all evil!

Nevertheless, it's possible to talk about the relative performance of switch vs. if/else with the Java compiler optimizations. First note that in Java, switch statements operate on a very limited domain -- integers. In general, you can view a switch statement as follows:

where c_0, c_1, ..., and c_N are integral numbers that are targets of the switch statement, and <condition> must resolve to an integer expression.

If this set is "dense" -- that is, (max(ci) + 1 - min(ci)) / n > α, where 0 < k < α < 1, where k is larger than some empirical value, a jump table can be generated, which is highly efficient.

If this set is not very dense, but n >= β, a binary search tree can find the target in O(2 * log(n)) which is still efficient too.

For all other cases, a switch statement is exactly as efficient as the equivalent series of if/else statements. The precise values of α and β depend on a number of factors and are determined by the compiler's code-optimization module.

Finally, of course, if the domain of <condition> is not the integers, a switch
statement is completely useless.

+1. There is a good chance that time spent on network I/O is easily eclipsing this particular issue.
–
Adam PaynterJan 18 '10 at 14:13

1

It should be noted that switches work with more than just ints. From the Java Tutorials: "A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer (discussed in Numbers and Strings)." Support for String is more recent addition; added in Java 7. docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
–
atraudesSep 11 '14 at 19:49

1

@jhonFeminella Could you please compare BIG O notion effects for Java7 String in Swtich compared to String in if / else if ..?
–
Kanagavelu SugumarNov 19 '14 at 10:57

Could you please (sometime) elaborate a bit on how you did benchmark this?
–
DerMikeMay 5 '14 at 11:47

Thank you very much for your update. I mean, they differ by one order of magnitude - wich is possible of course. Are you sure that the compiler did not just optimze the switches away?
–
DerMikeMay 5 '14 at 12:52

@DerMike I don't remember how I got the old results. I got very different today. But try it yourself and let me know how it turns out.
–
BitterblueMay 5 '14 at 13:58

when i run it on my laptop ; switch time needed: 3585, if/else time needed: 3458 so if/else is better :) or not worse
–
halilApr 22 at 9:32

@halil 2nd sentence of the accepted answer is absolutely right. In your case I would take switch anyways. The times aren't that different.
–
BitterblueApr 27 at 9:25

I remember reading that there are 2 kinds of Switch statements in Java bytecode. (I think it was in 'Java Performance Tuning' One is a very fast implementation which uses the switch statement's integer values to know the offset of the code to be executed. This would require all integers to be consecutive and in a well-defined range. I'm guessing that using all the values of an Enum would fall in that category too.

I agree with many other posters though... it may be premature to worry about this, unless this is very very hot code.

+1 for the hot code comment. If its in your main loop its not premature.
–
KingAndrewFeb 4 '14 at 23:56

Yes, javac implements switch several different ways, some more efficient than others. In general, the efficiency will be no worse than a straight-forward "if ladder", but there are enough variations (especially with the JITC) that it's hard to be much more precise than that.
–
Hot LicksNov 19 '14 at 12:40

Cliff gives an example (finishing on Slide 30) showing that even with the CPU doing register-renaming, branch prediction, and speculative execution, it's only able to start 7 operations in 4 clock cycles before having to block due to two cache misses which take 300 clock cycles to return.

So he says to speed up your program you shouldn't be looking at this sort of minor issue, but on larger ones such as whether you're making unnecessary data format conversions, such as converting "SOAP → XML → DOM → SQL → …" which "passes all the data through the cache".

For most switch and most if-then-else blocks, I can't imagine that there are any appreciable or significant performance related concerns.

But here's the thing: if you're using a switch block, its very use suggests that you're switching on a value taken from a set of constants known at compile time. In this case, you really shouldn't be using switch statements at all if you can use an enum with constant-specific methods.

Compared to a switch statement, an enum provides better type safety and code that is easier to maintain. Enums can be designed so that if a constant is added to the set of constants, your code won't compile without providing a constant-specific method for the new value. On the other hand, forgetting to add a new case to a switch block can sometimes only be caught at run time if you're lucky enough to have set your block up to throw an exception.

Performance between switch and an enum constant-specific method should not be significantly different, but the latter is more readable, safer, and easier to maintain.

Time taken for String in Switch :3235 Time taken for String in if/else if :3143 Time taken for String in Map :4194 Time taken for String in ENUM :2866
–
halilApr 22 at 9:36

@halil I am not sure how this code works on different environments, but you have mentioned if/elseif is better than Switch and Map, that i am not able to convince since if/elseif has to perform more no of times equals comparison.
–
Kanagavelu SugumarMay 20 at 11:36