简体   繁体   English

在PHP中评估布尔变量:应该使用If / Else还是Switch?

[英]Evaluating a boolean variable in PHP: Should one use If/Else or Switch?

I love getting myself into these ridiculous situations where I over-evaluate my coding practices, so here goes! 我喜欢让自己陷入这些荒谬的情况,在这些情况下我对我的编码实践进行了过高的评估,所以这里就来了!

This question probably transcends PHP (as well as sanity). 这个问题可能超越了PHP(以及理智)。 When evaluating a Boolean variable, which of these is best practice? 在评估布尔变量时,哪种最佳实践? (assume that there's too much //do stuff for a ternary) (假设有太多//do stuff三元操作)

if ($bool) {
    // do true stuff
} else {
    // do false stuff
}

or 要么

switch ($bool) {
    case true:
        // do true stuff
        break;
    default:
        // do false stuff
        break;
}

I'm interested more in performance and/or idiosyncratic considerations than blanket statements like "If/Else looks better," "Always use Switch," or "Do what you feel is right." 我对性能和/或特质性注意事项更感兴趣,而不是像“如果/其他看起来更好”,“始终使用Switch”或“做正确的事”之类的笼统声明。

That is, unless there really isn't a difference. 也就是说,除非真的没有区别。

Use the if-else version. 使用if-else版本。 It's very clear and easy to understand. 这非常清楚且易于理解。

You shouldn't really use switch unless you have multiple (> 2) values to switch on. 除非您有多个(> 2)值可以打开,否则不应真正使用switch You gain nothing using switch in this case (other than making your code less comprehensible). 在这种情况下,使用switch不会获得任何收益(除了使您的代码难以理解之外)。

If there was any difference in performance, the if-else version would be faster, although if was there any difference it would really be negligible. 如果性能上有任何差异,则if-else版本会更快,尽管如果有任何差异,则实际上可以忽略不计。

This would be a micro-optimization if anything. 如果有的话,这将是微优化。 Don't do it. 不要这样 Before you introduce any "optimizations" to your code, profile it and identify your bottlenecks. 在对代码进行任何“优化”之前,先对其进行概要分析并确定瓶颈。

Just in case, you should also check that your variable is really a boolean (and not "", 0, or null which may also evaluate to false) 为了以防万一,您还应该检查您的变量是否确实是布尔值(而不是“”,0或null,其值也可能为false)

if($bool === false) {
 // false stuff
} else if($bool === true) {
 // true stuff
} else {
 /// WTF???
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM