3 ms·
As yes, the classic "I can outsmart the compiler". I've been down the exact rabbithole, before, but with java. There are 2 different bytecodes for representing
by jcdavis 9y ago
As yes, the classic "I can outsmart the compiler".
I've been down the exact rabbithole, before, but with java. There are 2 different bytecodes for representing a switch statement: tableswitch, which is dense (has a case for every key from X to Y), and lookupswitch, which is sparse. Of course the dense one must be better, I thought: O(1) vs O(log n) ! Maybe if I added a few more cases manually to my switch statement to cover missing holes, my lookupswitch would become a tableswitch and my hot loop would be faster.
Turns out, of course, that not only is O(1) not necessarily any faster than O(log n) when n is small and the constant factor is large (see this article), but in fact its irrelevant since the hotspot uses the same function to generate the IR for both bytecodes (http://hg.openjdk.java.net/jdk9/jdk9/hotspot/file/b756e7a2ec33/src/share/vm/opto/parse2.cpp#l512 http://hg.openjdk.java.net/jdk9/jdk9/hotspot/file/b756e7a2ec... ), and thus the decision about whether to use a jumptable or binary search is entirely unreleated to the bytecode that represents the switch statement :)
- naasking 9y agoNot only that, but the O(log n) sparse table has multiple branch points that are more predictable, so the branch predictor works better. It can be faster overall than a single highly unpredictable branch point.