Hacker News new | ask | show | jobs
by tkho 6171 days ago
This is complete garbage. Even allowing for it being a microbenchmark, each iteration contains a System.out.println that takes thousands of times more cycles than the conditional.
1 comments

In addition, this varies greatly depending on the values you're matching against (how efficiently can it be compiled?) and what compiler is being used, even in just the Java space.
And if you are using a JIT that optimizes frequent code; how easily the branches are predictable and a host of other factors. Also, I don't think this comparison is even useful: clearly if-else and switch-case have different use-cases.

Some others have also hinted at using an array of function pointers and indexing by switch variable. This looks cleaner, but is not necessarily faster, since each call then involves chasing down a memory-pointer (this is also the general argument against virtual functions).

I'm not sure how valid this C-argument is in Java world, but I believe pointer chasing is a major performance problem (C# requires an explicit virtual declaration on functions for the same reason).

> Some others have also hinted at using an array of function pointers and indexing by switch variable.

Doing this explicitly makes no sense -- I'm pretty sure the compiler will compile the switch this way if its heuristics determine that it the fastest way.