views:

69

answers:

2

When using a switch() statement, you add break; in between separate case: declarations. But what about the last one?

Normally I just leave it off, but I'm wondering if this has some performance implication I'm not thinking about?

I've been wondering about this for a while and don't see it asked elsewhere on Stack-O, but sorry if I missed it.

I'm mainly asking this question regarding Javascript, although I'm guessing the answer will apply to all switch() statements.

+2  A: 

It's completely unnecessary from a performance stand-point, but a very good habit to maintain, since you might forget to add the break when you introduce more cases. Obviously this doesn't apply to default.

Marcelo Cantos
*"Obviously this doesn't apply to default."* Sure it does, `default` doesn't have to be the last case (although that's where *I* always put it).
T.J. Crowder
+7  A: 

Performance should not be a consideration at all. Even if some language or implementation has a performance difference that's measurable in a micro-benchmark, it would never cause a real-world performance issue.

I think the most important issue is consistency and maintainability. If you leave off the last break and then another developer adds another case statement without realizing you left off the break, the behavior would change. It's really the second developer's fault for not noticing the break is missing, but it could have been avoided by being consistent and having the break on all case clauses.

Sam
+1 There's just no good reason for leaving it off, really.
T.J. Crowder
Ah yeah good point, I'm sold :)
Jon Raasch