Switch() Statement Usage

switch() statement usage

Well, timing to the rescue again. It seems switch is generally faster than if statements.
So that, and the fact that the code is shorter/neater with a switch statement leans in favor of switch:

# Simplified to only measure the overhead of switch vs if

test1 <- function(type) {
switch(type,
mean = 1,
median = 2,
trimmed = 3)
}

test2 <- function(type) {
if (type == "mean") 1
else if (type == "median") 2
else if (type == "trimmed") 3
}

system.time( for(i in 1:1e6) test1('mean') ) # 0.89 secs
system.time( for(i in 1:1e6) test2('mean') ) # 1.13 secs
system.time( for(i in 1:1e6) test1('trimmed') ) # 0.89 secs
system.time( for(i in 1:1e6) test2('trimmed') ) # 2.28 secs

Update With Joshua's comment in mind, I tried other ways to benchmark. The microbenchmark seems the best. ...and it shows similar timings:

> library(microbenchmark)
> microbenchmark(test1('mean'), test2('mean'), times=1e6)
Unit: nanoseconds
expr min lq median uq max
1 test1("mean") 709 771 864 951 16122411
2 test2("mean") 1007 1073 1147 1223 8012202

> microbenchmark(test1('trimmed'), test2('trimmed'), times=1e6)
Unit: nanoseconds
expr min lq median uq max
1 test1("trimmed") 733 792 843 944 60440833
2 test2("trimmed") 2022 2133 2203 2309 60814430

Final Update Here's showing how versatile switch is:

switch(type, case1=1, case2=, case3=2.5, 99)

This maps case2 and case3 to 2.5 and the (unnamed) default to 99. For more information, try ?switch

Usage of switch statement in Java

I always use a clause default, regardless of the language you are working.

Things can and do go wrong. The values will not be what you expect, and so on.

switch (myVar) {
case 1: ......; break;
case 2: ......; break;
default: throw new RuntimeException("myVar invalid " + myVar);
}

Is my code complex enough for switch statement usage in Swift

The ultimate test is to just write out both and compare.

When switch is better

When you're dealing with a situation that favours a switch over an if/else ladder, you code will look like:


if something == 1 {
foo()
} else if something == 2 {
bar()
} else if something == 3 {
baz()
} else {
quux()
}

As you can see, all the bracketing, repeated keywords (else, if) repeated operators == and repeated instance of the same identifier (something) add a bunch of noise with really little value. Compare to the switch:

switch something {
case 1: foo()
case 2: bar()
case 3: baz()
default: quux()
}

When if/else if/else is better

You'll find yourself writing a switch where the switched variable isn't really being matched much, but instead you have a bunch of where clauses that check a lot of unrelated conditions. Compare:

switch something {
case 1: foo()
case _ where case2_1() || case2_2(): bar()
case _ where case3(): baz()
case _ where case4(): quux()
}

vs.

if something == 1 || case1() { foo() }
else if case2_1() || case2_2() { bar() }
else if case3() { baz() }
else if case4() { quux() }

Don't forget about polymorphism!

Whenever possible, try to break up complex switching logic into dynamic calls to methods on an object. This allows you to separate the logic of each case into a separate class, where all related logic can be grouped.

How do i use switch statement inside a method such that the method can return a char value which is acquired by the switch statement inside it?

Concerning your question:

  • the last return is not needed, just end switch with default clause
    and return default value there.
  • there is no need to use break stetements, since you are using
    return on each case

Also, if you are limiting yourself to only use switch, then this is one simpler way to achieve your goal:

char calculate(int[] scores) {
double averageScore = Arrays.stream(scores).average().getAsDouble();
int nearestMultipleOfFive = 5 * ((int) averageScore / 5);
switch (nearestMultipleOfFive) {
case 100:
case 95:
case 90: return 'O';
case 85:
case 80: return 'E';
case 75:
case 70: return 'A';
case 65:
case 60:
case 55: return 'P';
case 50:
case 45:
case 40: return 'D';
default: return 'E';
}
}

When to use a switch statement in Java

Well, switch feels "lighter" in many cases than an if/else if ladder, in my opinion. Basically you don't have that much syntax with braces and parentheses in the way of your code. That being said, switch inherits C's syntax. That means you have break and only a single scope for variables unless you introduce new blocks.

Still, the compiler is able to optimize switch statements into a lookup table and perform compile-time checking for literals when dealing with enumerations. So, I'd suggest that it's usually preferable to use switch over if/else if if you're dealing with numeric or enum types.

Avoid the usage of a switch statement when parsing

Check this out,

// Parent Class to group them
class Fruit {
var baseValue: Any
required init(_ this: Any) {
baseValue = this
(self as? Apple)?.color = this as! String
(self as? Banana)?.isTasty = this as! Bool
// You can add more subclasses here
}
}

class Apple: Fruit, Equatable {
var color = ""


func hash(into hasher: inout Hasher) {
hasher.combine(color)
}
static func == (lhs: Apple, rhs: Apple) -> Bool {
return lhs.color == rhs.color
}
}

class Banana: Fruit, Equatable {
var isTasty = false

func hash(into hasher: inout Hasher) {
hasher.combine(isTasty)
}
static func == (lhs: Banana, rhs: Banana) -> Bool {
return lhs.isTasty == rhs.isTasty
}
}

It's a little annoying that they have to conform to Fruit, Hashable, and Equatable. But it let's you do this, which answers your question:

let input: [(Fruit.Type,Any)] = [(Apple.self, "green"),(Banana.self, true)]

for (type, value) in input {
// Now you don't need that switch statement
let foo = type.init(value)
// Now you can use `as?` to find out what it is

print((foo as? Banana)?.isTasty)
// See, it prints `nil` first, then `Optional(true)` next.
// Which is how we want it to run
}


However, I think we can do even better.

enum Fruit {
case apple(color: String)
case banana(isTasty: Bool)
}

let input: [Fruit] = [.apple(color: "red"), .banana(isTasty: true)]

Much better.

Replacements for switch statement in Python?

The original answer below was written in 2008. Since then, Python 3.10 (2021) introduced the match-case statement which provides a first-class implementation of a "switch" for Python. For example:

def f(x):
match x:
case 'a':
return 1
case 'b':
return 2
case _:
return 0 # 0 is the default case if x is not found

The match-case statement is considerably more powerful than this simple example.


You could use a dictionary:

def f(x):
return {
'a': 1,
'b': 2,
}[x]

Can you connect two cases of a switch statement using a comma

Your original code segment uses fall-through to give the same response for both cases; some people find this difficult to read and follow. Java 12 gave us two related features that people find help clean up their switch statements, one of which you've discovered here:

  1. cases can be comma separated rather than relying on fall-through
  2. the arrow label can be used instead of the colon and break; commands.

Therefore, if you find yourself not liking fall-through, and not wanting to worry about whether you remembered your break commands, you can write the switch as follows:

switch (element) {
case hi, hello -> // do something here
case goodbye, bye -> // do something else here
}

Notice that in this case, we don't have any break statements, but there is no fall-through between the hi case and the bye case; they are separate due to the arrow label.



Related Topics



Leave a reply



Submit