【问题标题】:PHP switch statement VS if elseif statement benchmarkPHP switch 语句 VS if elseif 语句基准测试
【发布时间】:2015-07-19 11:23:35
【问题描述】:

我检查这个PHP website benchmark 检查switch statement VS if else if statement。我看到了这个结果:

switch 和 if 结构之间有区别吗?调用 1'000x

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

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

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

【问题讨论】:

  • === 比 == 快一点也不奇怪,因为如果两个值不相等,== 会尝试进行类型转换。 switch-case-statement 只有 2 个案例(和一个默认案例)。如果您有更多案例,我认为它会变得更快(相对于 if-elseif)。但是你的问题到底是什么?
  • 基准缺陷:第一种情况/如果比最后一种更常见还是更不常见?

标签: php mysql performance benchmarking


【解决方案1】:

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

请记住,这些差异非常小,并且会因算法中的任何低效率而相形见绌。因此,只有在确定已消除其他主要瓶颈后,才应调整此类细节。

【讨论】:

    【解决方案2】:

    默认 PHP 开关不完全匹配。

    exact match switch 的一些示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-14
      • 2016-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多