2015-07-19 179 views
-1

我检查这个PHP website benchmark进行检查switch statement VS if else if statement。我看到这样的结果:PHP switch语句VS if ifif语句基准

是否有开关和结构之间的区别?调用1'000x

  • 141%*if and elseif (using ==)*总时间:165μsview代码
  • 139%*if, elseif and else (using ==)*总时间:162μsview代码
  • 110%*if and elseif (using ===)*总时间:128μsview代码
  • 100%*if, elseif and else (using ===)*总时间:117微秒查看代码
  • 149%*switch/caseTotal*时间:174μsview代码
  • 181%*switch/case/default*总时间:211μsview代码

在结果我看到if else if更快(+ **100 %** *if, elseif and else (using ===)* Total time: 117 µsview code)。

这个基准是真的,if, elseif and else (using ===)更好更快,因为switch语句?!

+0

因为'=='会尝试进行类型转换(如果这两个值不相等),所以'==='比==快。 switch-case-statement只有2个案例(和一个默认案例)。如果你有更多的案例,我认为它会变得更快(相对于if-elseif)。但是,你的问题到底是什么? – AbcAeffchen

+0

基准瑕疵:是第一种情况/是否比上次更常见或不常见? –

回答

3

您是否得到完全相同的结果会因您评估的条件,设备,设置和其他因素而异。但是,通常if/elseif/else与严格比较(===)将优于switch。原因是switch uses "loose" (i.e., type-insensitive) comparison (==),这比类型敏感比较(===)慢。

请记住,这些差异非常小,并且会因为算法中的任何低效率而变得相形见绌。所以,在确定你已经消除了其他主要瓶颈之后,你只应该调整这样的细节。