log / if-else vs switch-case

Found an interesting problem in leetcode. The problem is quite simple, we need to reverse position for the vowels only and I can finish it by using 2 pointer. The interesting part for me is, how to determine the vowels? Of course we can use if-else or switch-case.

In code it will look like this:

  • if-else
func isVowel(r rune) bool {
    return r == 'a' || r == 'e' || r == 'i' || r == 'o' || r == 'u' || r == 'A' || r == 'E' || r == 'I' || r == 'O' || r == 'U'
}
  • switch-case
func isVowel(b byte) bool {
    switch b {
    case 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U':
        return true
    }
    return false
}

And how about the performance? I know maybe many people shouldn’t care, because the the impact may be only add some “micro-optimization”. However, I’m just curious. And then I found this article.

The conclusion is:

The results show that the switch statement is faster to execute than the if-else-if ladder. This is due to the compiler’s ability to optimize the switch statement. In the case of the if-else-if ladder, the code must process each if statement in the order determined by the programmer. However, because each case within a switch statement does not rely on earlier cases, the compiler is able to use branch tables in such a way as to provide the fastest execution.

For me, it nice to know that switch-case can be more faster than the if-else, even though I never found case that both of it will show huge difference performance. In general, just implement whichever design is clearer and more maintainable is the best consideration.

Written on 2024-07-08 11:38:00 +0700 Edited on 2024-07-08 11:56:00 +0700